【问题标题】:Remove the stuff up to and including the word in a string with multiple lines删除包含多行字符串中的单词的内容
【发布时间】:2016-08-30 13:07:14
【问题描述】:

我有以下多行字符串。我不能让它成为一行,因为它来自命令输出。例如:

my $myString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a 
type specimen book. It has survived not only five centuries, but also 
the leap into electronic typesetting, remaining essentially unchanged. 
It was popularised in the 1960s"

我想去掉包括“scrambled”这个词在内的东西

我在下面尝试过,但似乎不起作用。

if($myString =~ 's/.*(scrambled)//s')
{
  print "Match:   <$&>\n";
}

【问题讨论】:

    标签: linux perl shell


    【解决方案1】:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $myString = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
    when an unknown printer took a galley of type and scrambled it to make a 
    type specimen book. It has survived not only five centuries, but also 
    the leap into electronic typesetting, remaining essentially unchanged. 
    It was popularised in the 1960s";
    
    $myString =~ s/.*\bscrambled\b//s;
    
    print $myString;
    

    Demo

    【讨论】:

    • 如果字符串包含unscrambled...怎么办?更好的是我们将使用\bscrambled\b
    【解决方案2】:

    尝试去掉引号:

    if($myString =~ s/.*(scrambled)//s)

    通过引号,它试图匹配文字 s/.*(scrambled)//s 而不试图改变任何东西。如果没有引号,将看到“s”替代品。

    【讨论】:

      【解决方案3】:

      使用可以使用pre & post

      $myString =~ s/\bscrambled\b//ig && print $`.$';
      

      否则

      if($myString =~ s/\bscrambled\b//s)
      {
          print "Pre: <$`>\n";
          print "Match:   <$&>\n";
          print "Post:   <$'>\n";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-20
        • 2022-11-07
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多