【问题标题】:Not matching an optional colon at the end of the strings with a regex与正则表达式不匹配字符串末尾的可选冒号
【发布时间】:2014-08-20 15:54:07
【问题描述】:

我正在尝试创建一个正则表达式,用于提取字符串从开头到结尾的所有字符串,字符串末尾的冒号 (:) 除外。

字符串是:

ORA-06550: line 10, column 33:
ORA-20000: Schema "TEST" does not exist or insufficient privileges
PLS-00201: identifier 'A' must be declared:

在 Perl 语言的一个正则表达式中,我想捕获以下字符串:

ORA-06550: line 10, column 33
ORA-20000: Schema "TEST" does not exist or insufficient privileges
PLS-00201: identifier 'A' must be declared

到目前为止,我有以下正则表达式 (see online)::

/^(.*)(?::)?$/gm

我的问题是如何构造一个正则表达式,从第一个和第三个字符串中去掉冒号,同时捕获所有第二个字符串。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    您可以删除字符串末尾的冒号,而不是尝试提取所有内容。

    $str =~ s/:$//;
    

    【讨论】:

      【解决方案2】:

      你可以使用这个非贪婪的正则表达式:

      /^(.*?):?$/gm
      

      RegEx Demo

      【讨论】:

      • 没有必要使用惰性量词。它非常缓慢且不必要。
      • 不是这个^.+(?<!:$)
      【解决方案3】:

      我能想到的最简单的正则表达式是

         /(.+):$/
      

      所以要就地编辑缓冲区:

        $buffer =~ s/(.+):$/$1/;
      

      但你也可以考虑:

         chop $buffer if $buffer =~ /:$/;
      

      查找尾随冒号,并在找到时将其截断。

      【讨论】:

      • 我认为他有可能没有冒号的行。
      • 因此是“if and Chop”解决方案。并非每个解决方案都需要 s/// 运算符和复杂的正则表达式以及零宽度后视修饰符。一些时间和 if/then 就足够了,而且更清楚。事实上,“如果以冒号结尾则截断”不仅更清晰,而且实际上读起来就像代码的意图。
      【解决方案4】:

      试试这个。

      use warnings;
      use strict;
      @data = <DATA>;
      @remove = grep{s/(:$)?//g} @data;
      print "@remove\n";
      
      __DATA__
      ORA-06550: line 10, column 33:
      ORA-20000: Schema "TEST" does not exist or insufficient privileges
      PLS-00201: identifier 'A' must be declared:
      

      这段代码会从您的数据中删除 :。我添加了 ? 以匹配前面的字符 0 次或 1 次。

      【讨论】:

        【解决方案5】:

        这是最快最简单的方法

        /^.+(?<!:$)/mg
        

        【讨论】:

          猜你喜欢
          • 2019-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多