在 Perl 中捕获特殊字符之后的部分以及字符串



>我有以下字符串:

$string = 'perl/abc.t wstat[0]';

我需要从字符串中提取部分 abc.t。我尝试了以下正则表达式,只得到了 abc。变量 $1 中的部分。

 if ($string =~ qr{^.*perl/(S+)S+}) {
    print Dumper $1;
}

这给出了 1 美元作为"abc"。正则表达式的新手。

您将S声明为两次,这意味着它应该匹配两个非空格字符(可能的最小匹配(。所以你的正则表达式不能考虑.t所以你的正则表达式应该是

演示

perl/(S+)s+

演示

perl/([^s]+)

请参阅此调试器 请参阅步骤 12 13

对于您的第一个S+abc.t匹配(步骤 12(。

然后你提到了另一个S+.因此,您的正则表达式涉及回溯以匹配另一个非空格字符(步骤 13(。

查看您的输入字符串:

'perl/abc.t wstat[0]';
           ▲
           └────────➔ That's a space

您的模式是^.*perl/(S+)S+} :也就是说,您想在perl/之后一个接一个地找到两个空格字符的跨度(顺便说一句,如果您只是要查找"从一开始就寻找除换行符以外的任意数量的字符的跨度"(,您可能不需要锚定模式(。

贪婪地满足perl/两个跨度的非空格字符要求的唯一方法是将字符序列abc.(所有非空格(放在第一个跨度中,并将最后一个剩余的字符t放在第二个跨度中。

use strict;
use warnings;
my $string = 'perl/abc.t wstat[0]';
if ( $string =~ m{ perl/ (S+) }x ) {
    print "Basename is '$1'n";
}

use re 'debug'use re 'debugcolor'以获取有关程序中正则表达式的更多详细信息。在这种情况下,请注意:

Compiling REx " ^.* perl/ (S+) "
Final program:
   1: SBOL /^/ (2)
   2: STAR (4)
   3:   REG_ANY (0)
   4: EXACT <perl/> (7)
   7: OPEN1 (9)
   9:   PLUS (11)
  10:     NPOSIXD[s] (0)
  11: CLOSE1 (13)
  13: END (0)

Compiling REx " perl/ (S+) "
Final program:
   1: EXACT <perl/> (4)
   4: OPEN1 (6)
   6:   PLUS (8)
   7:     NPOSIXD[s] (0)
   8: CLOSE1 (10)
  10: END (0)

如果这太复杂,还有 YAPE::Regex::解释:

C:Temp> perl -MYAPE::Regex::Explain -e "print YAPE::Regex::Explain->new(qr{perl/(S+)S+})->explain"
The regular expression:
(?-imsx:perl/(S+)S+)
matches as follows:
NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  perl/                    'perl/'
----------------------------------------------------------------------
  (                        group and capture to 1:
----------------------------------------------------------------------
    S+                      non-whitespace (all but n, r, t, f,
                             and " ") (1 or more times (matching the
                             most amount possible))
----------------------------------------------------------------------
  )                        end of 1
----------------------------------------------------------------------
  S+                      non-whitespace (all but n, r, t, f,
                           and " ") (1 or more times (matching the
                           most amount possible))
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

最新更新