在 Perl 中匹配边界和选择选项


在 Perl 中匹配边界

\b 在 Perl 中匹配任何单词边界,边界定义为 \w 类和 \W 类之间的差异。因为 \w 包括单词的字符,而 \W 则相反,所以这通常意味着单词的终止。\B 断言匹配不构成单词边界的任何位置。例如,−

/\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat'
/\Bcat\B/ # Matches 'verification' but not 'the cat on the mat'
/\bcat\B/ # Matches 'catatonic' but not 'polecat'
/\Bcat\b/ # Matches 'polecat' but not 'catatonic'

在 Perl 中选择选项

| 字符就像 Perl 中的标准或按位或运算符。它指定正则表达式或组内的备选匹配。例如,要在表达式中匹配“cat”或“dog”,可以使用 −

if ($string =~ /cat|dog/)

您可以将表达式的各个元素组合在一起,以支持复杂的匹配。可以像这样进行两项独立测试来搜索两个人的姓名 −

if (($string =~ /Martin Brown/) || ($string =~ /Sharon Brown/))
This could be written as follows
if ($string =~ /(Martin|Sharon) Brown/)

更新于: 2019-11-29

236 次访问

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.