【问题标题】:Perl regex match has multiple empty linesPerl 正则表达式匹配有多个空行
【发布时间】:2017-08-02 19:23:26
【问题描述】:

我正在尝试用 perl 解析一个字符串并将匹配项放入一个数组中。

例如。 "FUNC1(VALUE1) VALUE1、VALUE2、FUNC2(FUNC1(VALUE3)) VALUE3、VALUE4、FUNC3(VALUE5) VALUE5"

输出:

FUNC1(VALUE1) VALUE1
VALUE2
FUNC2(FUNC1(VALUE3)) VALUE3
VALUE4
FUNC3(VALUE5) VALUE5

我的代码:

my $in = "FUNC1(VALUE1) VALUE1, VALUE2, FUNC2(FUNC1(VALUE3)) VALUE3, VALUE4, FUNC3(VALUE5) VALUE5";

my @cols = ($in =~ /((?&full_m)),?
(?(DEFINE)
            (?<full_m>(?&full_f)|(?&word))
            (?<full_f>(?&func)\s(?&word))
            (?<func>(?&word)\((?&worf)\))
            (?<worf>(?&func)|(?&word))
            (?<word>\s*\w+\s*)
        )/gx);
print "$in\n";

my $count = 1;
foreach (@cols) {
    print "$count: $_\n";
    ++$count;
}

问题是我得到了匹配项,但之后还有 5 个空匹配项。

1: FUNC1(VALUE1) VALUE1
2: 
3: 
4: 
5: 
6: 
7:  VALUE2
8: 
9: 
10: 
11: 
12: 
13:  FUNC2(FUNC1(VALUE3)) VALUE3
14: 
15: 
16: 
17: 
18: 
19:  VALUE4
20: 
21: 
22: 
23: 
24: 
25:  FUNC3(VALUE5) VALUE5
26: 
27: 
28: 
29: 
30: 

【问题讨论】:

  • 您的意思是在其中使用worf 而不是word
  • @cols 中的结果包含整个匹配项,还包含您在模式中定义的每个组的内容。这就是你获得 5 个空物品的原因。
  • 为什么它也有组?我以为它只会显示括号内的内容?
  • (?(DEFINE)...) 中的组也在括号内。
  • split /,/ 有什么问题?

标签: regex perl


【解决方案1】:

除了将组 1 存储到 col 的数组之外,这也是一样的。

my $in = "FUNC1(VALUE1) VALUE1, VALUE2, FUNC2(FUNC1(VALUE3)) VALUE3, VALUE4, FUNC3(VALUE5) VALUE5";
my @cols;
while ($in =~ /((?&full_m)),?(?(DEFINE)(?<full_m>(?&full_f)|(?&word))(?<full_f>(?&func)\s(?&word))(?<func>(?&word)\((?&worf)\))(?<worf>(?&func)|(?&word))(?<word>\s*\w+\s*))/gx)
{
   push @cols, $1;
}
print "$in\n";

my $count = 1;
foreach (@cols) {
    print "$count: $_\n";
    ++$count;
}

输出

FUNC1(VALUE1) VALUE1, VALUE2, FUNC2(FUNC1(VALUE3)) VALUE3, VALUE4, FUNC3(VALUE5) VALUE5
1: FUNC1(VALUE1) VALUE1
2:  VALUE2
3:  FUNC2(FUNC1(VALUE3)) VALUE3
4:  VALUE4
5:  FUNC3(VALUE5) VALUE5

为了更好地查看正则表达式,需要格式化

 ( (?&full_m) )                # (1)
 ,?
 (?(DEFINE)
      (?<full_m>                    # (2 start)
           (?&full_f) 
        |  (?&word)
      )                             # (2 end)
      (?<full_f>                    # (3 start)
           (?&func) \s (?&word)
      )                             # (3 end)
      (?<func>                      # (4 start)
           (?&word) \( (?&worf) \)
      )                             # (4 end)
      (?<worf>                      # (5 start)
           (?&func) 
        |  (?&word)
      )                             # (5 end)
      (?<word> \s* \w+ \s* )        # (6)
 )

【讨论】:

  • 谢谢,这成功了!我仍然不确定为什么我的版本添加了匹配的组。
  • 查看格式化的正则表达式,其他组在你做@ary = $s ~= //g;时记录。但是,当您从 (?(DEFINE)) 将组作为函数调用时,它们的组值将被覆盖,但其匹配项会返回给调用者。
  • 再次感谢您的快速解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
相关资源
最近更新 更多