gpt4 book ai didi

javascript - 正则表达式验证字符的单次出现

转载 作者:行者123 更新时间:2023-11-30 09:04:25 26 4
gpt4 key购买 nike

我想检查输入字符串以验证正确的文本。验证将使用 javascript 完成,现在我正在使用此代码:

keychar = String.fromCharCode(keynum);
var text = txtBox.value + keychar;
textcheck = /(?!.*(.)\1{1})^[fenFN,]*$/;
return textcheck.test(text);

允许的字符串例如:
f
电子
f,e
n,f,e,F,N

不允许的例子:


f,f
f,ee
f,e,n,f
n,,(虽然这可能没问题)

这可以用 Javascript 中的正则表达式解决吗?

最佳答案

虽然可以使用正则表达式,但它会产生一个相当大的正则表达式,可能难以理解(因此难以维护)。我会按照 Benjam 的建议选择“手动”选项。

然而,使用正则表达式,您可以这样做:

var tests = [
'f',
'e',
'f,e',
'n,f,e,F,N',
'ff',
'fe',
'f,f',
'f,ee',
'f,e,n,f',
'n,,',
'f,e,e'
];

for(var i = 0; i < tests.length; i++) {
var t = tests[i];
print(t + ' -> ' + (t.match(/^([a-zA-Z])(?!.*\1)(,([a-zA-Z])(?!.*\3))*$/) ? 'pass' : 'fail'));
}

将打印:

f -> pass
e -> pass
f,e -> pass
n,f,e,F,N -> pass
ff -> fail
fe -> fail
f,f -> fail
f,ee -> fail
f,e,n,f -> fail
n,, -> fail
f,e,e -> fail

正如您在 Ideone 上看到的那样.

一个小的解释:

^                     # match the start of the input
([a-zA-Z]) # match a single ascii letter and store it in group 1
(?!.*\1) # make sure there's no character ahead of it that matches what is inside group 1
( # open group 2
,([a-zA-Z])(?!.*\3) # match a comma followed by a single ascii letter (in group 3) that is not repeated
)* # close group 2 and repeat it zero or more times
$ # match the endof the input

关于javascript - 正则表达式验证字符的单次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6382630/

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