ITPub博客

首页 > 应用开发 > IT综合 > 用perl 正则表达式处理文本(二)

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

原创 IT综合 作者:ljj21153 时间:2007-11-01 22:54:24 0 删除 编辑

注意: &&代替反斜线


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/,如需转载,请注明出处,否则将追究法律责任。

下一篇: symbian怪异问题集
请登录后发表评论 登录
全部评论

注册时间:2007-12-16

  • 博文量
    18
  • 访问量
    17061