【问题标题】:RegEx pattern test is failing in javascript正则表达式模式测试在 javascript 中失败
【发布时间】:2016-09-13 07:36:34
【问题描述】:

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

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

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

给定的字符串是有效的,它只包含大写和小写字母。不知道模式有什么问题。

【问题讨论】:

  • 你认为这个正则表达式有什么作用?
  • * 也不匹配。
  • 检查任何不包含 patt 变量的字符。
  • @prababuddy 对您收到的答案有何反馈?
  • @ThomasAyoub,抱歉延迟响应......它工作正常,但我有一个场景来捕获非键盘字符(如版权符号或任何其他语言字符),在这种情况下,正则表达式模式失败了......例如......如果我输入“Ä/ä”这个,正则表达式模式无法捕捉到这个字符。关于这个的任何想法......这对我会有很大的帮助......

标签: javascript regex


【解决方案1】:

这是你的代码:

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

正则表达式

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

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

只需添加锚点:

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

【讨论】:

  • 空字符串仍然会传递表达式。
  • @WiktorStribiżew 感谢分享,我会看看,学习并纠正我的答案
  • 很确定 OP 不希望 '' 传递表达式。当然,我可能是错的。如果不是,请将* 更改为+
【解决方案2】:

请注意:

  • 通过代码中的否定条件 (!patt.test...) 更好地表示对缺失模式的搜索。
  • 您需要通过在某些字符前加上反斜杠 (\) 来转义某些字符,例如 .()? 等。

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

这将按预期打印false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多