[英]Javascript RegExp: Word boundaries and punctuation marks
我正在尝试使用javascript的RegExp来匹配完整的单词,但是当这些单词以标点符号作为边界时,它不起作用。 即
(new RegExp("\\b"+RegExp.escape("why not")+"\\b", 'i')).test("why not you foolish")
正确匹配。 和:
(new RegExp("\\b"+RegExp.escape("why not")+"\\b", 'i')).test("why nots you foolish")
正确地不匹配。 问题在于,当单词以“?”结尾时,这是行不通的:
(new RegExp("\\b"+RegExp.escape("why not?")+"\\b", 'i')).test("why not? you foolish")
有什么建议么?
注意:我正在使用此功能来转义:
# Escape characters for regexp
RegExp.escape = (text) ->
text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
?
在RegExp中具有特殊含义,应转义。
好的,我明白了,您正在尝试逃避它……但是,并非所有浏览器都内置了RegExp.escape
方法,这似乎是问题。 原因
(new RegExp("\\b"+"why not\?"+"\\b", 'i')).test("why not? you foolish")
按预期工作(返回true)。
这是我使用的代码:
if (typeof RegExp.escape == "undefined") {
RegExp.escape = function(str) {
return str.replace(/([()\[\]\\\/+*?.-])/g, "\\$1");
}
}
“?” 是Regex的特殊字符。 我相信您需要摆脱它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.