/null/g.test('null null')出现意外的正则表达式行为(Unexpected regular expression behavior with /null/g.

编程入门 行业动态 更新时间:2024-10-11 23:20:01
/null/g.test('null null')出现意外的正则表达式行为(Unexpected regular expression behavior with /null/g.test('null null')) var re = /null/g; re.test('null null'); //> true re.test('null null'); //> true re.test('null null'); //> false

什么!?!?

我尝试在Chrome,Firefox,Safari中进行测试。 使用正则表达式与RegExp构造函数,但无济于事。

为什么会这样?

JS Bin附加演示

var re = /null/g; re.test('null null'); //> true re.test('null null'); //> true re.test('null null'); //> false

WHAT!?!?

I tried testing in Chrome, Firefox, Safari. Used regex with RegExp constructor, but to no avail.

Why is this happening?

JS Bin with additional demo

最满意答案

全局正则表达式(使用g标志的表达式)是特殊的。 如果您多次在同一个字符串上调用它们,它们会搜索连续的匹配项。 由于您的测试字符串恰好包含两个null匹配项,因此第三次调用RegExp#test将返回false (无法找到连续的第三个匹配项)。

要解决此问题,您可以放弃g标志,如下所示:

var re = /null/

console.log(re.test('null null')) //=> true
console.log(re.test('null null')) //=> true
console.log(re.test('null null')) //=> true 
  
 

Global regular expressions (those using the g flag) are special. If you call them on the same string multiple times, they search for successive matches. Since your test string contains exactly two matches for null, the third call to RegExp#test returns false (a third match in a row cannot be found).

To fix this problem, you can abandon the g flag like so:

var re = /null/

console.log(re.test('null null')) //=> true
console.log(re.test('null null')) //=> true
console.log(re.test('null null')) //=> true 
  
 

更多推荐

本文发布于:2023-07-29 05:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1313020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   正则表达式   test   null   behavior

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!