Regex只匹配整個單詞我有一個regex表達式,用于查找存儲在數(shù)據(jù)庫中的詞匯表中包含的給定內容塊(大小寫不敏感)中的所有單詞。這是我的模式:/($word)/i問題是如果我用/(Foo)/i然后像這樣的詞Food匹配。單詞的兩邊需要有空格或單詞邊界。如何將表達式修改為只匹配單詞Foo當它是一個詞在一個句子的開頭,中間,還是結尾?
4 回答

慕哥6287543
TA貢獻1831條經(jīng)驗 獲得超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條經(jīng)驗 獲得超6個贊
var myReg = new RegExp(‘\\\\b’+ variable + ‘\\\\b’, ‘g’)

HUX布斯
TA貢獻1876條經(jīng)驗 獲得超6個贊
/\b($word)\b/i
/(?:\W|^)(\Q$word\E)(?:\W|$)/i
- 4 回答
- 0 關注
- 1073 瀏覽
添加回答
舉報
0/150
提交
取消