#!/usr/bin/perl
use 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"
使用单词边界:
或者如果你在搜索“S.p.E.C.T.R.E.”,就像在西南的例子中一样:
使用
\b
可以产生令人惊讶的结果。你最好弄清楚是什么把一个词从它的定义中分离出来,并把这些信息整合到你的模式中。输出:
要匹配任何一个单词,您可以使用模式
(\w+)
假设您正在使用PCRE或类似的工具:
以上截图摘自本例:http://regex101.com/r/cU5lC2
用
(\w+)
匹配命令行中的所有单词我将使用Ubuntu 12.10上的phpsh interactive shell通过名为preg_match的方法演示PCRE regex engine
启动phpsh,将一些内容放入变量中,匹配word。
preg_match方法使用PHP语言中的PCRE引擎来分析变量:
$content1
、$content2
和$content3
和(\w)+
模式。$content1和$content2至少包含一个单词,$content3不包含。
用
(dart|fart)
匹配命令行中的许多文字单词变量gun1和gun2包含字符串dart或fart。gun4没有。然而,查找单词
fart
匹配farty
可能是一个问题。要解决此问题,请在regex中强制使用单词边界。将命令行中的文字单词与单词边界匹配
所以它和前面的例子一样,只是内容中不存在单词边界为
\b
的单词fart
。相关问题 更多 >
编程相关推荐