免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2270 | 回复: 7
打印 上一主题 下一主题

谁能解释一下perl的规则式的意思? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-05-04 15:51 |只看该作者 |倒序浏览
#!/usr/bin/perl
use strict;
use warnings;

my $string1 = "madam im adam";
my $string2 = "the motto means something";
my $string3 = "no palindrome here";

findPalindrome( $string1 );
findPalindrome( $string2 );
findPalindrome( $string3 );

sub findPalindrome
{
   my $string = shift();

   if ( $string =~
           /(\w)\W*(\w)\W*(\w)\W*(\w)\W*\4\W*\3\W*\2\W*\1/
        or $string =~
           /(\w)\W*(\w)\W*(\w)\W*(\w)\W*\3\W*\2\W*\1/ ) {
      print "$string - ",
            "has a palindrome of at least 7 characters.\n";
   }
   else {
      print "$string - has no long palindromes.\n";
   }
}

那位大侠能解释一下:/(\w)\W*(\w)\W*(\w)\W*(\w)\W*\4\W*\3\W*\2\W*\1/和/(\w)\W*(\w)\W*(\w)\W*(\w)\W*\3\W*\2\W*\1/的意思

论坛徽章:
0
2 [报告]
发表于 2008-05-04 16:03 |只看该作者
看不懂,学习一下 !!!

论坛徽章:
0
3 [报告]
发表于 2008-05-04 16:07 |只看该作者
建议楼主去本版的精华部分了解下perl的正则表达式吧!
你这正则表达式挺简单的!

论坛徽章:
0
4 [报告]
发表于 2008-05-04 16:42 |只看该作者
这个正则式用来判断字符串

has a palindrome of at least 7 characters

或者

has no long palindromes

人家自己说的很清楚嘛

论坛徽章:
0
5 [报告]
发表于 2008-05-04 16:42 |只看该作者

回复 #3 changejun 的帖子

为什么不能讲一下呢?不要吝啬吗。

论坛徽章:
0
6 [报告]
发表于 2008-05-04 16:45 |只看该作者
原帖由 cobrawgl 于 2008-5-4 16:42 发表
这个正则式用来判断字符串

has a palindrome of at least 7 characters

或者

has no long palindromes

人家自己说的很清楚嘛



只是想有人给详细的解释一下,那2个表达式的意思。虚心向大家请教。谢谢!主要是后面的\4 \3 \2 \1不太明白。

[ 本帖最后由 paub 于 2008-5-4 16:47 编辑 ]

论坛徽章:
0
7 [报告]
发表于 2008-05-04 16:53 |只看该作者
Learning Perl 4th version

8.6. The Match Variables
So far, when we've put parentheses into patterns, they've been used only for their ability to group parts of a pattern together. But parentheses also trigger the regular expression engine's memory. The memory holds the part of the string matched by the part of the pattern inside parentheses. If there are more than one pair of parentheses, there will be more than one memory. Each regular expression memory holds part of the original string, not part of the pattern.

Since these variables hold strings, they are scalar variables; in Perl, they have names like $1 and $2. There are as many of these variables as there are pairs of memory parentheses in the pattern. As you'd expect, $4 means the string matched by the fourth set of parentheses.


  1. /(\w)  ----> \1 or $1
  2. \W*
  3. (\w)  ----> \2 or $2
  4. \W*
  5. (\w)  ----> \3 or $3
  6. \W*
  7. (\w)  ----> \4 or $4
  8. \W*
  9. \4
  10. \W*
  11. \3
  12. \W*
  13. \2
  14. \W*
  15. \1/
复制代码

论坛徽章:
0
8 [报告]
发表于 2008-05-04 16:58 |只看该作者
perl 还会提醒你,\1 最好写成 $1 之类的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP