在 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.