Javascript RegExp:字边界和标点符号

时间:2012-03-06 19:35:39

标签: javascript regex

我试图使用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, "\\$&")

2 个答案:

答案 0 :(得分:3)

?在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");
    }
}

答案 1 :(得分:1)

“?”是正则表达式的特殊字符。我相信你需要逃避它。