Javascript 在正则表达式范围内转义点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10397968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escape dot in a regex range
提问by gdoron is supporting Monica
For some reason those two regex act the same way:
出于某种原因,这两个正则表达式的行为方式相同:
"43\gf..--.65".replace(/[^\d.-]/g, "");? // 43..--.65
"43\gf..--.65".replace(/[^\d\.-]/g, "");? // 43..--.65
In the first regex I don't escape the dot(.
) while in the second regex I do(\.
).
在第一个正则表达式中,我没有转义点(.
),而在第二个正则表达式中我没有转义(\.
)。
What are the differences and why they act the same?
有什么区别,为什么它们的行为相同?
采纳答案by usoban
Because the dot is inside character class (square brackets []
).
因为点在字符类(方括号[]
)内。
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
看看http://www.regular-expressions.info/reference.html,它说(在 char 类部分下):
Any character except ^-]\ add that character to the possible matches for the character class.
除了 ^-]\ 之外的任何字符都会将该字符添加到字符类的可能匹配项中。
回答by jbabey
The dot operator .
does not need to be escaped inside of a character class []
.
点运算符.
不需要在字符类内转义[]
。
回答by MMiroslav
If you using JavaScript to test your Regex, try \\.
instead of \.
.
如果您使用 JavaScript 来测试您的 Regex,请尝试\\.
代替\.
.
It acts on the same way because JS remove first backslash.
它的作用相同,因为 JS 删除了第一个反斜杠。
回答by Rob I
On this web page, I see that:
在这个网页上,我看到:
"Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash."
“请记住,点不是字符类中的元字符,因此我们不需要用反斜杠对其进行转义。”
So I guess the escaping of it is unnecessary...
所以我想逃避它是不必要的......