perl正则中的命名捕获

回复 收藏
脚本中用到的测试文本内容
cat ./test.txt
Helo, This is a test file.
This file contain a story about fred flintstone and his friend.
One day fred went to shoping, he met Sam who is his friend.
Sam was also for shopping. So they got together.
lalalal fred or wilma.
When they on their way home, they met frederick and Alfred.
Frederick and Alfred want to look after their granpa Mr. Slate.
this line just test Fred
and this line FRED
add this line Bamm-Bamm
wilma and fred
aa
abcdefhijk
foot
goooood

不使用命名捕获脚本为:
  1. #! /usr/bin/perl
  2. if (! open TEST,"./test.txt") {
  3.         die $!;
  4. }
  5. while () {
  6.         if (/(fred\b).*(sam\b)/i) {
  7.                 print "$1 $2\n";
  8.         }
  9. }
运行结果为:
fred Sam

使用命名捕获脚本为:
  1. #! /usr/bin/perl
  2. if (! open TEST,"./test.txt") {
  3.         die $!;
  4. }
  5. while () {
  6.         if (/(?fred\b).*(?sam\b)/i) {
  7.                 print "$+{name1} $+{name2}\n";
  8.         }
  9. }
运行结果为:
fred Sam
2012-12-17 17:50 举报
已邀请:

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
可选评分理由: