You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript正则表达式需求:拒绝连续字符/数字及重复字符输入

Combining Both Validation Rules into a Single Regex

Great question! Let's merge your existing duplicate-character regex with a pattern that catches consecutive (forward or backward) letters/numbers, so you can validate both rules in one go.

Breakdown of Each Rule

First, let's recap what we need to block:

  • Consecutive characters (forward or backward): e.g., 123, jkl, zyx, 321
  • Repeated identical characters: e.g., aa, 000, aabb, pp22 (your existing rule already handles this)

Building the Consecutive Character Regex

To catch forward/backward consecutive sequences, we use positive lookaheads to check if the next character is adjacent in the ASCII table:

  • Forward consecutive: [a-y](?=[b-z]) (lowercase), [A-Y](?=[B-Z]) (uppercase), [0-8](?=[1-9]) (numbers)
  • Backward consecutive: [b-z](?=[a-y]) (lowercase), [B-Z](?=[A-Y]) (uppercase), [1-9](?=[0-8]) (numbers)

Merging Both Rules

Combine the consecutive character pattern with your existing duplicate pattern using a pipe | (which acts as an OR operator in regex). The final regex will match any input that violates either rule.

Final JavaScript Implementation

Here's how to use it in code:

const isValidInput = (input) => {
  // Regex matching either repeated characters OR consecutive (forward/backward) letters/numbers
  const invalidPattern = /([a-zA-Z0-9])\1+|([a-y](?=[b-z])|[A-Y](?=[B-Z])|[0-8](?=[1-9])|[b-z](?=[a-y])|[B-Z](?=[A-Y])|[1-9](?=[0-8]))/;
  // Return true if input has no violations, false otherwise
  return !invalidPattern.test(input);
};

// Test the function with sample inputs
console.log(isValidInput("abc123")); // false (forward consecutive letters + numbers)
console.log(isValidInput("zyx321")); // false (backward consecutive letters + numbers)
console.log(isValidInput("aabb00")); // false (repeated characters)
console.log(isValidInput("x1y2z3")); // true (no violations)
console.log(isValidInput("pQrS")); // true (non-consecutive, non-repeated)

How It Works

  • ([a-zA-Z0-9])\1+: Matches any letter/number that repeats 2 or more times (your original rule)
  • The second half of the regex uses lookaheads to detect adjacent characters:
    • For forward sequences: Ensures the next character is the immediate successor (e.g., a followed by b)
    • For backward sequences: Ensures the next character is the immediate predecessor (e.g., b followed by a)

Edge Cases to Note

  • This regex will catch any 2+ consecutive adjacent characters (even within longer sequences like abcd or 4321)
  • It handles mixed cases (e.g., AbC won't trigger the consecutive rule since case changes break the ASCII sequence)

内容的提问来源于stack exchange,提问作者Rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:03:31