免费注册 查看新帖 |

Chinaunix

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

[已解决]求助:正则表达式匹配换行符的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-11-26 12:04 |只看该作者 |倒序浏览
本帖最后由 bzdghdn 于 2010-11-26 13:10 编辑

小弟想写一个正则表达式检测一个字符串中是否不含有换行符,我觉的表达式"^[^\n]+$"表示字符串从开始到结束由一个或多个非换行符组成,所以
  1. #!/usr/bin/perl
  2. my %string = ("abc\n"=>'abc\n',"\nabc"=>'\nabc',"a\nbc"=>'a\nbc');
  3. #换行符在最后,换行符在最前,换行符在中间
  4. for(keys %string)
  5. {
  6.         if (/^[^\n]+$/)
  7.         {
  8.                 print $string{$_},' match ^[^\n]+$',"\n";
  9.         }
  10.         else{
  11.                 print $string{$_},' not match ^[^\n]+$',"\n";
  12.         }
  13. }
复制代码
运行结果
  1. a\nbc not match ^[^\n]+$
  2. \nabc not match ^[^\n]+$
  3. abc\n match ^[^\n]+$
复制代码
从上面程序看到如果换行符在最末的时候,正则表达式^[^\n]+$能够匹配"abc\n"。这点我想不通,请高手指点。
因为如果\n换成其它字符的时候,好像都不能匹配,比如
  1. #!/usr/bin/perl
  2. my %string = ("abc\r"=>'abc\r',"\rabc"=>'\rabc',"a\rbc"=>'a\rbc');
  3. for(keys %string)
  4. {
  5.         if (/^[^\r]+$/)
  6.         {
  7.                 print $string{$_},' match ^[^\r]+$',"\n";
  8.         }
  9.         else{
  10.                 print $string{$_},' not match ^[^\r]+$',"\n";
  11.         }
  12. }
复制代码
结果
  1. a\rbc not match ^[^\r]+$
  2. abc\r not match ^[^\r]+$
  3. \rabc not match ^[^\r]+$
复制代码
是不是因为换行符有什么特殊性?

论坛徽章:
0
2 [报告]
发表于 2010-11-26 13:09 |只看该作者
本帖最后由 bzdghdn 于 2010-11-26 13:11 编辑

在perlretut中有下面的介绍
The anchor ^ means match at the beginning of the string and the anchor $ means match at the end of the string, or before a newline at the end of the string. Here is how they are used:

    "housekeeper" =~ /keeper/;    # matches
    "housekeeper" =~ /^keeper/;   # doesn't match
    "housekeeper" =~ /keeper$/;   # matches
    "housekeeper\n" =~ /keeper$/; # matches
$ means match at the end of the string, or before a newline at the end of the string.
看来换行符在字符串的末尾确实是一个比较特殊的情况

我试了试,java和python中的正则表达式也是同样的情况

论坛徽章:
46
15-16赛季CBA联赛之四川
日期:2018-03-27 11:59:132015年亚洲杯之沙特阿拉伯
日期:2015-04-11 17:31:45天蝎座
日期:2015-03-25 16:56:49双鱼座
日期:2015-03-25 16:56:30摩羯座
日期:2015-03-25 16:56:09巳蛇
日期:2015-03-25 16:55:30卯兔
日期:2015-03-25 16:54:29子鼠
日期:2015-03-25 16:53:59申猴
日期:2015-03-25 16:53:29寅虎
日期:2015-03-25 16:52:29羊年新春福章
日期:2015-03-25 16:51:212015亚冠之布里斯班狮吼
日期:2015-07-13 10:44:56
3 [报告]
发表于 2010-11-26 13:12 |只看该作者
本帖最后由 zhlong8 于 2010-11-26 13:15 编辑

默认情况下 $ 匹配字符串结尾,或字符尾部的一个\n前面。注意它只是个位置信息,不实际匹配任何字符

/s /m 修饰符会影响 . 和 ^$ 的意义,了解细节自己去看文档 perlretut perlre

论坛徽章:
0
4 [报告]
发表于 2010-11-26 13:16 |只看该作者
谢谢zhlong8
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP