gpt4 book ai didi

javascript - 正则表达式模式测试在 JavaScript 中失败

转载 作者:行者123 更新时间:2023-12-03 06:07:35 25 4
gpt4 key购买 nike

我有下面的正则表达式来验证字符串..

var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
var res = patt.test(str);

结果总是给出 true,但我认为它会给出 false.. 因为我检查了 patt 变量中没有的任何模式...

给定的字符串有效,并且仅包含大写和小写字母。不确定该模式有什么问题。

最佳答案

这是您的代码:

var str = "Thebestthingsinlifearefree";
var patt = /[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
console.log(patt.test(str));

正则表达式

/[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g

将匹配任何内容,因为由于量词*它接受长度为0的匹配

只需添加 anchor :

var str = "Thebestthingsinlifearefree";
var patt = /^[^0-9A-Za-z !\\#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]*$/;
console.log(patt.test(str));

<小时/>

这是您的正则表达式的解释:

[^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

关于javascript - 正则表达式模式测试在 JavaScript 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39464559/

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