Regex只匹配整个单词我有一个regex表达式,用于查找存储在数据库中的词汇表中包含的给定内容块(大小写不敏感)中的所有单词。这是我的模式:/($word)/i问题是如果我用/(Foo)/i然后像这样的词Food匹配。单词的两边需要有空格或单词边界。如何将表达式修改为只匹配单词Foo当它是一个词在一个句子的开头,中间,还是结尾?
4 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
\b
#!/usr/bin/perluse strict; use warnings;use re 'debug';my $str = 'S.P.E.C.T.R.E. (Special Executive for Counter-intelligence, Terrorism, Revenge and Extortion) is a fictional global terrorist organisation';my $word = 'S.P.E.C.T.R.E.';if ( $str =~ /\b(\Q$word\E)\b/ ) { print $1, "\n";}
Compiling REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" Final program: 1: BOUND (2) 2: OPEN1 (4) 4: EXACT (9) 9: CLOSE1 (11) 11: BOUND (12) 12: END (0) anchored "S.P.E.C.T.R.E." at 0 (checking anchored) stclass BOUND minlen 14 Guessing start of match in sv for REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P .E.C.T.R.E. (Special Executive for Counter-intelligence,"... Found anchored substr "S.P.E.C.T.R.E." at offset 0... start_shift: 0 check_at: 0 s: 0 endpos: 1 Does not contradict STCLASS... Guessed: match at offset 0 Matching REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P.E.C.T.R.E. (Special Exec utive for Counter-intelligence,"... 0 | 1:BOUND(2) 0 | 2:OPEN1(4) 0 | 4:EXACT (9) 14 | 9:CLOSE1(11) 14 | 11:BOUND(12) failed... Match failed Freeing REx: "\b(S\.P\.E\.C\.T\.R\.E\.)\b"
FFIVE
TA贡献1797条经验 获得超6个赞
var myReg = new RegExp(‘\\\\b’+ variable + ‘\\\\b’, ‘g’)
HUX布斯
TA贡献1876条经验 获得超6个赞
/\b($word)\b/i
/(?:\W|^)(\Q$word\E)(?:\W|$)/i
- 4 回答
- 0 关注
- 992 浏览
添加回答
举报
0/150
提交
取消