gpt4 book ai didi

javascript - REGEX - 输入必须有 x 个唯一数字

转载 作者:行者123 更新时间:2023-11-29 19:05:45 25 4
gpt4 key购买 nike

我想知道是否有人知道正则表达式检测至少使用了 x 位数字的方法。

例如,如果我输入一个 6 位数字 111222,但我的正则表达式表明必须至少有 3 个唯一数字,这将导致有效失败。

但如果我有 123456 那会通过,因为使用了三个以上的唯一数字。

类似的东西(显然它不会像下面那样。)

/^[0-9]{6}*3$/

非正则方式

var telcstart = $('#num').val(),
telc1 = (telcstart.match(/1/g) || []).length,
telc2 = (telcstart.match(/2/g) || []).length,
telc3 = (telcstart.match(/3/g) || []).length,
telc4 = (telcstart.match(/4/g) || []).length,
telc5 = (telcstart.match(/5/g) || []).length,
telc6 = (telcstart.match(/6/g) || []).length,
telc7 = (telcstart.match(/7/g) || []).length,
telc8 = (telcstart.match(/8/g) || []).length,
telc9 = (telcstart.match(/9/g) || []).length,
telc0 = (telcstart.match(/0/g) || []).length,
totaltelc = "a:" + telc1 + " b:" + telc2 + " c:" + telc3 + " d:" + telc4 + "e:" + telc5 + " f:" + telc6 + " g:" + telc7 + " h:" + telc8 + " i:" + telc9 + " j:" + telc0,
finaltelc = (totaltelc.match(/0/g) || []).length;

if (finaltelc <= 8) {
alert('passed');
} else {
alert('failed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" id="num" value="123451212111">

最佳答案

^(?=.*(.)(?!$|.*\1))(?=.*(?!\1)(.)(?!$|.*\2))[0-9]+$

function check(value) {
var res = document.getElementById('result');
if (/^(?=.*(.)(?!$|.*\1))(?=.*(?!\1)(.)(?!$|.*\2))[0-9]+$/.test(value)) {
res.innerText = '✓ OK';
} else {
res.innerText = '✗ No match';
}
}
<p>Enter a number with ≥3 different digits</p>
<p><input type=text onkeyup='check(this.value)'> <span id=result></span></p>

让我们把它分开:

^
(?=
.*(.) # Pick any character in the string as group 1
(?!$|.*\1) # Ensure this is not the last character, but is the last unique character
)
(?=
.*(?!\1)(.) # Pick another character in the string as group 2
(?!$|.*\2) # Same condition as above
)
[0-9]+
$

第一个条件确保有一个像 ??1??a 这样的字符串。第二个条件确保像 ???2?b 这样的字符串,其中 1a2b12。由此我们可以得出结论,至少有 3 个不同的字符。


这可以很容易地概括为例如至少需要 8 个不同的字符:

^
(?=.*(.)(?!$|.*\1))
(?=.*(?!\1)(.)(?!$|.*\2))
(?=.*(?!\1|\2)(.)(?!$|.*\3))
(?=.*(?!\1|\2|\3)(.)(?!$|.*\4))
(?=.*(?!\1|\2|\3|\4)(.)(?!$|.*\5))
(?=.*(?!\1|\2|\3|\4|\5)(.)(?!$|.*\6))
(?=.*(?!\1|\2|\3|\4|\5|\6)(.)(?!$|.*\7))
[0-9]+
$

因为 JavaScript 最多只支持 \9,所以您不能使用此方法检查超过 10 个不同的字符。在这一点上,你真的应该质疑正则表达式是否是这项工作的正确工具😉。

关于javascript - REGEX - 输入必须有 x 个唯一数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42979963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com