【问题标题】:Need to match multiple pattern in the same line - Perl需要在同一行中匹配多个模式 - Perl
【发布时间】:2014-11-23 02:27:09
【问题描述】:

我需要在同一行匹配多个模式。例如,在这个文件中:

Hello, Chester [McAllister;Scientist] lives in Boston [Massachusetts;USA;Fenway Park] # McAllister works in USA
I'm now working in New-York [NYC;USA] # I work in USA
...

首先,我想将每个字符串匹配到括号中,因为知道可以有多个模式,而且我们可以在括号中放置 1 到 n 个字符串,括号中总是用分号分隔.

最后,对于每一行,我需要将值与位于# 之后的字符串进行比较。比如第一句话,我想比较一下:

[McAllister;Scientist] & [Massachusetts;USA;Fenway Park] TO "McAllister works in USA"

【问题讨论】:

  • 你的意思是这个\[[^;\n]*(?:;[^;\n]*)+\]regex101.com/r/uT5cC0/2'
  • 你想做什么,把它们放到一个数组中?
  • @AvinashRaj 我试过这个if($sentence =~ /(\[[^;]*(?:;[^;]*)+\])/g){ print $1."\n"; },但第一行的结果是:[McAllister;Scientist] lives in Boston [Massachusetts;USA;Fenway Park]
  • @sln 为什么不呢。最后,我需要将用分号分隔的每个值与字符串进行比较。我编辑答案更清楚。

标签: regex perl


【解决方案1】:

最简洁的方法可能是使用正则表达式查找由方括号分隔的所有嵌入序列,然后使用mapsplit 将这些序列分隔为术语。

这个程序演示。

请注意,我假设文件中的所有数据都已读入单个标量变量。您可以将其更改为一次处理一行,但前提是括号内的子序列永远不会拆分为多行

use strict;
use warnings;

my $s = <<END_TEXT;
Hello, Chester [McAllister;Scientist] lives in Boston [Massachusetts;USA;Fenway Park] # McAllister works in USA
I'm now working in New-York [NYC;USA] # I work in USA
END_TEXT

my @data = map [ split /;/ ], $s =~ / \[ ( [^\[\]]+ ) \] /xg;

use Data::Dump;
dd \@data;

输出

[
  ["McAllister", "Scientist"],
  ["Massachusetts", "USA", "Fenway Park"],
  ["NYC", "USA"],
]

【讨论】:

    【解决方案2】:

    试试这个

    这也是你所期望的。

    use strict;
    use warnings;
    open('new',"file.txt");
    my @z =map{m/\[[\w;\s]+\]/g} <new>;
    print "$_ ,",foreach(@z);
    

    您实际上需要匹配[] 中由; 分隔的单词。

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多