正则表达式字边界和特殊字符 [英] Regular Expression Word Boundary and Special Characters
问题描述
我有一个正则表达式来转义搜索字符串中的所有特殊字符.这很好用,但是我似乎无法让它与单词边界一起使用.例如,用干草堆
I have a regular expression to escape all special characters in a search string. This works great, however I can't seem to get it to work with word boundaries. For example, with the haystack
add +
或
add (+)
和针
+
正则表达式 /\+/gi
匹配+".但是正则表达式 /\b\+/gi
没有.关于如何完成这项工作的任何想法?
the regular expression /\+/gi
matches the "+". However the regular expression /\b\+/gi
doesn't. Any ideas on how to make this work?
使用
add (plus)
作为干草堆和 /\bplus/gi
作为正则表达式,它匹配得很好.我就是不明白为什么转义字符有问题.
as the haystack and /\bplus/gi
as the regex, it matches fine. I just can't figure out why the escaped characters are having problems.
推荐答案
\b
是一个零宽度断言:它不消耗任何字符,它只是断言某个条件在给定位置成立.单词边界断言该位置要么在一个单词字符前面不跟一个,要么在一个单词字符后面不跟一个.(单词字符"是字母、数字或下划线.)在您的字符串中:
\b
is a zero-width assertion: it doesn't consume any characters, it just asserts that a certain condition holds at a given position. A word boundary asserts that the position is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. (A "word character" is a letter, a digit, or an underscore.) In your string:
add +
...开头有一个单词边界,因为 a
前面没有单词字符,第二个 d
后面有一个,因为它后面没有一个单词字符.正则表达式 (/\b\+/
) 中的 \b
试图在空格和 +
之间进行匹配,但不匹配工作,因为这两个都不是单词字符.
...there's a word boundary at the beginning because the a
is not preceded by a word character, and there's one after the second d
because it's not followed by a word character. The \b
in your regex (/\b\+/
) is trying to match between the space and the +
, which doesn't work because neither of those is a word character.
这篇关于正则表达式字边界和特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!