perl 的正则表达式匹配(一)

本文详细介绍了Perl语言中的正则表达式用法,包括匹配操作的简写形式、匹配选项修饰符、锚点的使用及绑定操作符。通过实例展示了如何进行大小写不敏感匹配、跨行匹配以及模式中的空格处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意: 由于此blog不能显示反斜线,故用&&代替反斜线.

1. Matches with m//.

匹配操作(m/string/) 的简写形式 /string/, 也可以用m/string/的等价式m(string), m, m{string}, m[string],m,string,,m!string!,m^string^,等. 如果匹配,返回true,否则为false

2. Matches Option Modifiers

a. 大小写不敏感选项 /i

如果没有/i,是大小写敏感的.

print "Would you like to play a game? ";
chomp($_ = );
if (/yes/i) { # case-insensitive match
print "In that case, I recommend that you go bowling.n";
}

b. 匹配任何字符 /s

默认情况下.不匹配新行,而只能在一行内匹配,如果加了/s选项则可以匹配新行,就象[&&d&&D]一样能匹配任意字符。

$_ = "I saw Barneyndown at the bowling alleynwith Frednlast night.n";
if (/Barney.*Fred/s) {
print "That string mentions Fred after Barney!n";
}

note:Without the /s modifier, that match would fail since the two names aren't on the same line.

c. 允许模式中的空格选项 /x

默认的模式中如果有空格,表示匹配有空格的string,如果加上 /x 选项则忽略中间空格.(目的是使得模式清晰) 。

/-?d+.?d*/ # what is this doing?
/ -? d+ .? d* /x # a little better

/
-? # an optional minus sign
d+ # one or more digits before the decimal point
.? # an optional decimal point
d* # some optional digits after the decimal point
/x # end of pattern

#good style

d. 选项的复合.

if (/barney.*fred/is) { # both /i and /s
print "That string mentions Fred after Barney!n";
}

3. Anchors 锚.

行首标识符 ^

行尾标识符 $

“词”边界标识符 b, “词”可以由下划线,数字,字母组成。

/&&bfred&&b/将匹配单词fred, 不会匹配frederick, alfred.

/abc123&&b/可以匹配abc123- ,但abc123_却不可以。这就是因为下划线是“词”的边界,而横线不是词的边界。

4. The Binding Operator, =~ (绑定操作符)

默认匹配字符串变量是$_, 如 if (/ string /)....

如果要让指定的变量来匹配则需要绑定操作符 =~, 如下

my $some_other = "I dream of betty rubble.";
if ($some_other =~ /brub/) {
print "Aye, there's the rub.n";
}

又如

print "Do you like Perl? ";
my $likes_perl = ( =~ /byesb/i);
... # Time passes...
if ($likes_perl) {
print "You said earlier that you like Perl, so...n";
...

[@more@]

未完待续

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/88842/viewspace-979450/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/88842/viewspace-979450/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值