使用正则表达式从 Perl 中的字符串中删除它们周围的多余管道和文本



假设我有一个这样的字符串,我想在perl中处理。

hello|world|nice|to|meet|you

我想保留前三个管道符号及其周围的文本,并丢弃字符串的其余部分。所以,我最终会得到这个:

hello|world|nice|to

我想我想做这样的事情:

substitute (zero or more non-pipes followed by a pipe)[3 times] followed by the rest of the string with a back reference to the piece of the regex where I matched the 3 pipes and the characters around them. 

我不确定 perl 中的正则表达式语法。

我可以做我想做的事:

$str = "hello|world|nice|to|meet|you" ;
@a = split(/|/, $str) ;
print $a[0] . "|" . $a[1] . "|" . $a[2] . "|" . $a[3]

但是,我想看看如何使用正则表达式来做到这一点。

您可以使用此正则表达式:

s='hello|world|nice|to|meet|you'
perl -pe 's/^((?:[^|]*|){3}[^|]*).*/$1/' <<< "$s"

hello|world|nice|to

正则表达式详细信息:

  • ^: 开始
  • (:启动捕获组 #1
    • (?::启动非捕获组
      • [^|]*:匹配 0 或多个非管道的任何字符
      • |:匹配管道
    • ){3}:结束非捕获组。{3}匹配该组的 3 次重复
    • [^|]*:匹配 0 或多个非管道的任何字符
  • ):结束捕获组 #'
  • .*:匹配一切直到最后

Perl 代码

$str = "hello|world|nice|to|meet|you" ;
$str =~ s/^((?:[^|]*|){3}[^|]*).*/$1/;
print "$strn";

您可以使用()捕获:

$ cat foo.pl && ./foo.pl
#!/usr/bin/perl
$str = "hello|world|nice|to|meet|you" ;
$str =~ s/^(([^|]*|){3}[^|]*)|.*/$1/;
print STDOUT "$strn";
hello|world|nice|to

要删除除前 3 个管道和周围文本之外的所有管道和周围的文本,可以像这样完成:

$txt =~ s/^(?:[^|]*|){3}[^|]*K.*//s;

最新更新