【问题标题】:How do I extract the data that comes after a certain word?如何提取某个单词之后的数据?
【发布时间】:2012-06-20 18:51:58
【问题描述】:

Cross-posted at Perlmonks

$String = "hello I went to the store yesterday and the day after and the day after";

我只想打印单词i went to the store。我尝试了两种方法,都没有成功:

if ($String =~ /hello/i) {
    until ($String =~ /yesterday/i) {
        print "Summary: $'"
    }
}

这打印了整个字符串。我使用了 $' 函数,但它占用了太多数据。如何限制?

如果我只想打印“昨天和后天”怎么办?我如何才能开始匹配中间的脚本?

【问题讨论】:

标签: regex perl regex-greedy


【解决方案1】:

首先,以前的答案使用$1,但我讨厌在不需要时使用全局变量。这里不需要。

其次,以前的答案假设您不想捕获换行符,但您没有说任何类似的话。

修复:

if (my ($match) = $s =~ /hello (.*?) yesterday/s) {
   say $match;
}

最后,使用? greediness 修饰符可能会导致意外(尤其是当您在一个模式中使用多个时)。如果给了

hello foo hello bar yesterday

上面的正则表达式将捕获

foo hello bar

如果你愿意

bar

请改用以下内容:

if (my ($match) = $s =~ /hello ((?:(?!yesterday).)*) yesterday/s) {
   say $match;
}

(?:(?!STRING).)STRING 就像 [^CHAR]CHAR

【讨论】:

    【解决方案2】:

    这回答了最初的问题和后续问题。

    use strict;
    use warnings FATAL => 'all';
    my $String = 'hello I went to the store yesterday and the day after and the day after';
    my ($who_what_where) = $String =~ /hello (.*) yesterday/;
    # 'I went to the store'
    

    匹配字符串的中间是默认行为,和第一个例子没有什么不同。

    my ($when) = $String =~ /store (.*) and/;
    # 'yesterday and the day after'
    

    我不建议初学者使用$1$`,这通常是有问题的,请参阅Perl: Why doesn't eval '/(...)/' set $1?Perl doesn't update to next match 了解最近的示例如何在更复杂的程序中容易出错。相反我教的是简单使用匹配操作的返回值,它没有$1$`和朋友们的缺点。

    【讨论】:

      【解决方案3】:

      这是一个开始。

      if ($String =~ /hello (.*?) yesterday/i) {
          print $1;
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用括号 ()$1$2 用于第二个括号组等)来捕获文本。

        use strict;
        use warnings;  # always use these 
        
        my $string= "hello I went to the store yesterday and the day after " ;
        
        if (/hello (.*?) yesterday/i) {
            print "Summary: $1\n";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-14
          • 2021-10-14
          • 1970-01-01
          • 2021-11-11
          相关资源
          最近更新 更多