用perl 正则表达式处理文本(二)

注意: &&代替反斜线


3. 合并操作 join $glue, @pieces
把@pieces数组合并,元素间加$glue字符串

例8.
my $x = join ":", 4, 6, 8, 10, 12; # $x is "4:6:8:10:12"

例9.
my $y = join "foo", "bar"; # gives just "bar", since no fooglue is needed
my @empty; # empty array
my $empty = join "baz", @empty; # no items, so it's an empty string

例10.
my @values = split /:/, $x; # @values is (4, 6, 8, 10, 12)
my $z = join "-", @values; # $z is "4-6-8-10-12"

4. 列表上下文下的m//匹配操作.
一般情况下 =~ /pattern/ 操作返回true 或则false, 但当在数组或hash情况下
却会是数组或hash.

note:在前面有内置匹配变量数组$1,$2,$3,...好似有关联.

例11.
$_ = "Hello there, neighbor!";
my($first, $second, $third) = /(&&S+) (&&S+), (&&S+)/;
print "$second is my $third&&n";

例12.
my $text = "Fred dropped a 5 ton granite block on Mr. Slate";
my @words = ($text =~ /([a-z]+)/ig);
print "Result: @words";
# Result: Fred dropped a ton granite block on Mr Slate

例13.
my $data = "Barney Rubble Fred Flintstone Wilma Flintstone";
my %last_name = ($data =~ /(&&w+)&&s+(&&w+)/g);

5. 匹配的贪婪性.
$_ = "I thought you said Fred and Velma, not Wilma"
s#(.*)#$1#g; #matched "Velma, not Wilma" 贪婪匹配
s#(.*?)#$1#g; #matched $1="Velma", and $2="Wilma" 非贪婪匹配

同样的 /.+/ 和/.+?/是贪婪与非贪婪模式.
{5,10}? 和 {8, }?是非贪婪的.

6. 多行文本匹配.
通常情况下,锚^, $匹配字符串的开始, 结尾, 如果给定字符串是多行的
需要用到行始, 行尾匹配则可以加上匹配的m选项.

例14.
$_ = "I'm much better&&nthan Barney is&&nat bowling,&&nWilma.&&n";
print "Found 'wilma' at start of line&&n" if /^wilma&&b/im;

例15.
open FILE, $filename or die "Can't open '$filename': $!";
my $lines = join '', ;
$lines =~ s/^/$filename: /gm;

7. 非捕获性小括号
模式中的小括号, 如/(&&d+)(&&w+)/ 会被$1, $2捕获, 但如果是下面的情形
if (/(bronto)?saurus (steak|burger)/)
{
print "Fred wants a $2&&n";
}
结果怎么样了, $2是空或是steak, burger,好象无法正确取得steak或burger.
要正确取得值, 需要用非捕获性小括号, 如下
if (/(?:bronto)?saurus (steak|burger)/)
{
print "Fred wants a $1&&n"; #$1=="steak" or "burger"
}

[@more@]用perl 正则表达式处理文本 完

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值