簡體   English   中英

正則表達式 js 匹配字符串包含 0 或 1 個重復字符

[英]Regex js to match that a string contains 0 or 1 repeated characters

我有一個包含 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

我嘗試了這兩個正則表達式,但它們無法正常工作

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

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

這是我的鏈接:

這個問題不適合使用您提供的輸入的正則表達式,因為輸入不遵循正則模式(此外,您的字符串中的任何長度更改都難以處理)。 相反,我建議簡單地遍歷字符串並注意任何重復項。

這是執行此操作的一種方法:

 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'));

是的,你可以用正則表達式來做到這一點。 如果規則被破壞,則此正則表達式匹配。

 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/

如果字符串只有 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM