Javascript 正则表达式在不应该匹配逗号时匹配逗号
我无法弄清楚 Firefox 7.0.1 和 Google Chrome 14.0.835.202 中发生的这个 javascript 小奇怪现象(我没有测试过任何其他版本)。为什么 /[+-.]/g
除了匹配加号(+
)、破折号()之外,还匹配逗号(
)和句点(,
) -.
)?
// Firebug
>>> "Hello, World++--..".match(/[+-.]/g);
[",", "+", "+", "-", "-", ".", "."]
>>> "Hello, World".match(/[+-.]/g);
[","]
// Chrome Developer Tools:
> "Hello, World++--..".match(/[+-.]/g);
[",", "+", "+", "-", "-", ".", "."]
> "Hello, World".match(/[+-.]/g);
[","]
好吧,也许我需要转义句点 (.
)
// Firebug
>>> "Hello, World!".match(/[+-\.]/g);
[","]
// Chrome Developer Tools
> "Hello, World!".match(/[+-\.]/g);
[","]
不。但是,如果我更改加号 (+
) 和破折号 (-
) 的顺序,它将停止匹配逗号 (,
)。
// Firebug
>>> "Hello, World".match(/[-+.]/g);
null
// Chrome Developer Tools
> "Hello, World".match(/[-+.]/g);
null
这对我来说毫无意义。 Firefox 和 Chrome 都共享相同的正则表达式错误,这似乎很奇怪。有人知道这是为什么吗?
I cannot figure out this javascript little oddity that's occurs in Firefox 7.0.1 and Google Chrome 14.0.835.202 (I haven't tested any other versions). Why does /[+-.]/g
match commas (,
) in addition to plus signs (+
), dashes (-
) and periods (.
)?
// Firebug
>>> "Hello, World++--..".match(/[+-.]/g);
[",", "+", "+", "-", "-", ".", "."]
>>> "Hello, World".match(/[+-.]/g);
[","]
// Chrome Developer Tools:
> "Hello, World++--..".match(/[+-.]/g);
[",", "+", "+", "-", "-", ".", "."]
> "Hello, World".match(/[+-.]/g);
[","]
Okay, so maybe I need to escape the period (.
)
// Firebug
>>> "Hello, World!".match(/[+-\.]/g);
[","]
// Chrome Developer Tools
> "Hello, World!".match(/[+-\.]/g);
[","]
Nope. But if I change the order of the plus (+
) and dash (-
) it stops matching the comma (,
).
// Firebug
>>> "Hello, World".match(/[-+.]/g);
null
// Chrome Developer Tools
> "Hello, World".match(/[-+.]/g);
null
This makes no sense to me. It seems odd that both Firefox and Chrome would share the same regex bug. Does anybody know why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
[+\-.]
。-
屏蔽一个范围并且必须转义。Use
[+\-.]
.-
masks a range and must be escaped.在两个其他字符之间的方括号内使用
-
会匹配这些字符之间范围内的所有字符(包括这两个字符)。因此,+
是U+002B
,.
是U+002E
。该范围内的所有字符都将包括:它与您包含的 3 个字符以及另外一个字符相匹配,这只是一个令人困惑的巧合。您的答案就在您的问题中...将
-
移至方括号中的第一个字符:或者,您可以转义
-
:Using
-
within square brackets between two other characters matches all characters in the range between those characters, inclusive. So,+
isU+002B
and.
isU+002E
. All of the characters in that range would include:That it was matching the 3 characters you included plus one more is just a confusing coincidence. Your answer is in your question... Move the
-
to be the first character in the square brackets:Alternatively, you can escape the
-
: