【问题标题】:Question On Text Parsing In Perl关于Perl中的文本解析的问题
【发布时间】:2011-05-10 15:43:30
【问题描述】:

我想把这行解析成这样,

S1,F2  title including several white spaces  (abbr) single,Here<->There,reply

我想要如下的输出,

1
2
title including several white spaces
abbr
single
Here22There  # identify <-> and translate it to 22; 
reply

我想知道如何解析上面的行?

方法一。 我打算将整行分成四段,然后解析各个子段。

段 1。 S1,F2

段 2。 title including several white spaces

段 3。 abbr

段 4。 single,Here&lt;-&gt;There,reply

方法二。 我只是写了一个复杂的正则表达式语句来解析它。

哪种方法对我的实践更有意义?

感谢任何 cmets 或建议。

【问题讨论】:

标签: regex perl parsing text-parsing


【解决方案1】:

假设您的输入采用指定的格式,您可以使用如下正则表达式:

^S(\d+),F(\d+)\s+(.*?)\((.*?)\)\s+(.*?),(.*?),(.*)$

Codepad link

【讨论】:

  • 嗨。为什么你的表情以$(1 美元)结尾?我测试并发现它在有/没有$的情况下都能正常工作。
【解决方案2】:

关于你的第一种方法,你可以做的就是先用逗号分割字符串,比如

my $line =
 'S1,F4  title including several white spaces (abbr) single,Here<->There,reply';
 my ($field1, $field2, $field3, $field4) = split /,/, $line;

然后在字段上应用正则表达式包含子字符串S1 和F2 title including several white spaces (abbr) single like

my ($field5) = $field1 =~ /S(\d+)/;
my ($field6, $field7, $field8, $field9) = 
                    $field2 =~ m/^F(\d+)\s+(.*?)\((.*?)\)\s+(.*?)$/;

它适用于所有这些字符串,并有助于避免使用和制作复杂的正则表达式,

S1,F2  title including several white spaces  (abbr) single,Here<->There,reply
S1,F2  title including several white spaces  (abbr) single,Here<->There
S1,F2  title including several white spaces  (abbr) single,Here<->There,[reply]

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 2013-10-12
    • 2011-10-11
    • 2013-06-09
    • 2021-12-06
    • 1970-01-01
    • 2011-06-30
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多