正则表达式只匹配整个单词 [英] Regex match entire words only
问题描述
我有一个正则表达式,我用它来查找给定内容块中的所有单词,不区分大小写,包含在存储在数据库中的词汇表中.这是我的模式:
I have a regex expression that I'm using to find all the words in a given block of content, case insensitive, that are contained in a glossary stored in a database. Here's my pattern:
/($word)/i
问题是,如果我使用 /(Foo)/i
那么像 Food
这样的词会被匹配.单词两侧需要有空格或单词边界.
The problem is, if I use /(Foo)/i
then words like Food
get matched. There needs to be whitespace or a word boundary on both sides of the word.
如果Foo
是句首、句中或句尾的词,我如何修改表达式以仅匹配该词?
How can I modify my expression to match only the word Foo
when it is a word at the beginning, middle, or end of a sentence?
推荐答案
使用单词边界:
/\b($word)\b/i
或者如果您正在搜索S.P.E.C.T.R.E."就像 Sinan Ünür 的例子:
Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:
/(?:\W|^)(\Q$word\E)(?:\W|$)/i
这篇关于正则表达式只匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!