我在RegEx下方验证字符串..
var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
var res = patt.test(str);
结果将始终为true但我认为它会给出错误..因为我检查任何不在patt变量中的模式......
给定的字符串有效,它只包含带大写和小写字母的字母。不确定模式有什么问题。
答案 0 :(得分:1)
这是您的代码:
var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
console.log(patt.test(str));
&#13;
正则表达式
/[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g
将匹配任何内容,因为它接受长度为0的匹配,因为量词*
。
只需添加锚点:
var str = "Thebestthingsinlifearefree";
var patt = /^[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*$/;
console.log(patt.test(str));
&#13;
这是一个解释或你的正则表达式:
[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]* match a single character not present in the list below
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
0-9 a single character in the range between 0 and 9
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
! a single character in the list ! literally
\\ matches the character \ literally
#$%&()*+, a single character in the list #$%&()*+, literally (case sensitive)
\- matches the character - literally
. the literal character .
\/ matches the character / literally
:;<=>?@ a single character in the list :;<=>?@ literally (case sensitive)
\[ matches the character [ literally
\] matches the character ] literally
^_`{|}~ a single character in the list ^_`{|}~ literally
答案 1 :(得分:0)
请注意:
!patt.test...
)更好地表达对缺失模式的搜索。.
)来转义某些字符,例如(
,)
,?
,\
等。
var str = "Thebestthingsinlifearefree";
var patt = /[0-9A-Za-z !\\#$%&\(\)*+,\-\.\/:;<=>\?@\[\]^_`\{|\}~]/;
var res = !patt.test(str);
console.log(res);
&#13;
这将按预期打印false
。