【问题标题】:Particular line match in Regex PerlRegex Perl 中的特定行匹配
【发布时间】:2014-12-07 17:25:02
【问题描述】:

输入:

gis.google.com
CAT
DOG
gis1.goole.com
CAT gis.google.com
gis.google.com DOG

我使用下面的正则表达式来匹配每行的prticlar模式。

/^[\w]+\s+[\w]+[\.][\w]+[\.][\w]+$/mg

下面是匹配的

DOG
gis1.goole.com
CAT gis.google.com

但我只想匹配一行

   CAT gis.google.com

请帮我整理一下。提前致谢!

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    \s+ 替换为\h+,其中\s 将匹配空格和换行符,但\h 仅匹配水平空格。这就是为什么连续两行(DoG 和它的下一行)匹配的原因。并从您的正则表达式中删除所有不必要的字符类。

    ^\w+\h+\w+\.\w+\.\w+$
    

    DEMO

    【讨论】:

      【解决方案2】:

      你是如何使用正则表达式的?

      可以稍微简化一下,但是在使用逐行处理完成时它可以工作:

      while (<DATA>) {
          print if /^\w+\s+\w+[.]\w+[.]\w+$/;
      }
      
      __DATA__
      gis.google.com
      CAT
      DOG
      gis1.goole.com
      CAT gis.google.com
      gis.google.com DOG
      

      输出:

      CAT gis.google.com
      

      Live Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多