正则表达式js匹配字符串包含0或1个重复字符

时间:2017-01-15 15:21:50

标签: javascript

我有一个包含4位数的字符串。我需要检查这个字符串是否不超过1个重复数字。

此群组应匹配:

1234  match    // no repeated digits
1123  match    // only one repeated digit 1
1213  match
1231  match
1223  match
1233  match

不应匹配此群组:

1222  fail   //digit 2 repeated 3 times
2222  fail
1112  fail
1211  fail
1212  fail   // digits 1 and 2 repeated 2 times
1122  fail
1221  fail

我尝试了这2个正则表达式,但它们无法正常工作

  •   

    ^(:?!。(\ d)(()* \ 2)){4} $

  •   

    ^(:(\ d)(* \ 1 {2})!)。(?:?!(\ d)(\ 2)){3} $

以下是我的链接:

3 个答案:

答案 0 :(得分:1)

这个问题并不适合使用您提供的输入的正则表达式,因为输入不遵循常规模式(此外,您的字符串中的任何长度更改都难以处理)。相反,我建议简单地迭代字符串并注意任何重复。

以下是执行此操作的一种方法:



function almostUnique(input) {
    var hasDuplicate = false;
    var cache = new Set();
    for (var i = 0; i < input.length; i++) {
        if (cache.has(input[i])) {
            if (hasDuplicate) {
                return false; // We already have a duplicate, so this is the second duplicate
            }
            hasDuplicate = true;
        } else {
            cache.add(input[i])
        }
    }
    return true; // Only one duplicate, or no duplicates.
}

console.log('1234 match', almostUnique('1234'));
console.log('1123 match', almostUnique('1123'));
console.log('1213 match', almostUnique('1213'));
console.log('1231 match', almostUnique('1231'));
console.log('1223 match', almostUnique('1223'));
console.log('1233 match', almostUnique('1233'));

console.log('1222 fail', almostUnique('1222'));
console.log('2222 fail', almostUnique('2222'));
console.log('1112 fail', almostUnique('1112'));
console.log('1211 fail', almostUnique('1211'));
console.log('1212 fail', almostUnique('1212'));
console.log('1122 fail', almostUnique('1122'));
console.log('1221 fail', almostUnique('1221'));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

是的,您可以使用regexp执行此操作。如果规则被破坏,此正则表达式匹配。

const re = /(.).*\1.*\1|(.).*\2.*(.).*\3|(.).*(.).*\4.*\5|(.).*(.).*\7.*\6/;
//          ^^^^^^^^^^^                                                     a..a..a
//                      ^^^^^^^^^^^^^^^^                                    a..a..b..b
//                                       ^^^^^^^^^^^^^^^^                   a..b..a..b
//                                                        ^^^^^^^^^^^^^^^^  a..b..b..a

const data = [1234, 1123, 1213, 1231, 1223, 1233, 1222, 2222, 1112, 1211, 1212, 1122, 1221];

data.forEach(x => console.log(x, re.test(x) ? "fail" : "pass"));

如果您愿意事先对字符串进行排序,那么正则表达式只是

/(.)\1\1|(.)\2.*(.)\3/

答案 2 :(得分:0)

如果字符串只有4个字符,则此测试将等同于测试字符串中是否至少有3个不同的字符。所以这个功能会起作用:

function test(str){
    var chars = [];
    for(var i = 0; i < str.length; i++)
        if(chars.indexOf(str[i]) == -1)
            chars.push(str[i]);

    return chars.length >= 3;
}

<强>测试:

test("1123"); // true
test("1234"); // true
test("1211"); // false
test("1122"); // false