【问题标题】:Perl Regex Multiple Capture GroupsPerl 正则表达式多个捕获组
【发布时间】:2014-05-17 01:30:12
【问题描述】:

我永远不会说我是 regex 方面的专家,而且由于我缺乏理解,我确信我对此有疑问。如果有人可以请尝试向我解释如何处理这种情况,我将非常感激。

string = "hello.world with_args, and_more_args #plus a comment

正则表达式

/^\w*\.(\w+)\s+(.*?)([^#]*)$/

群组

1. world
2. with_args, and_more_args #
3. plus a comment

我希望的输出是

1.world
2.with_args, and_more_args
3.#plus a comment

任何建议都将不胜感激,如果您能在此过程中教我一些东西,我当然不会抱怨。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    你可以用这个:

    ^\w*\.(\w+)\s+(.*?) *(#[^#]*)$
    

    Online Demo

    • 要在最后一个组中捕获#,将# 包括在最后一个捕获组中很重要,即(#[^#]*)
    • 我在第 # 组和 #3 组之间添加了*,以避免在第 2 组中捕获尾随空格。

    【讨论】:

    • 谢谢,我知道我必须亲近。我非常感谢您的帮助和课程
    • 不客气,很高兴它起作用了,是的,你的正则表达式非常接近。
    【解决方案2】:

    最好在第二次捕获时检查非散列字符;否则模式将只匹配带有注释的行。

    我建议这个

    use strict;
    use warnings;
    
    my $s = 'hello.world with_args, and_more_args #plus a comment';
    
    $s =~ / \w*\.(\w+) \s+ ([^#]*) (#.*)? /x;
    
    print "$_\n" for $1, $2, $3;
    

    输出

    world
    with_args, and_more_args 
    #plus a comment
    

    【讨论】:

    • 感谢您的来信。实际上,我确实弄清楚了我自己的那部分(在必须沮丧之后),但我当然感谢您的努力。
    猜你喜欢
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多