Regex 使用正则表达式从Perl中的字符串中删除额外的管道及其周围的文本
假设我有这样一个字符串,我想用perl处理它Regex 使用正则表达式从Perl中的字符串中删除额外的管道及其周围的文本,regex,perl,Regex,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 refer
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.
$str = "hello|world|nice|to|meet|you" ;
@a = split(/\|/, $str) ;
print $a[0] . "|" . $a[1] . "|" . $a[2] . "|" . $a[3]
我不确定perl中的正则表达式语法
hello|world|nice|to|meet|you
我可以做我想做的事情:
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.
$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"
正则表达式详细信息:
^:开始
:启动捕获组1
?::启动非捕获组
[^ |]*:匹配0个或更多非管道字符
\|:配管
{3} :结束非捕获组。{3} 匹配该组的3次重复
[^ |]*:匹配0个或更多非管道字符
:结束捕获组`
*匹配所有内容直到结束
Perl代码:
您可以使用此正则表达式:
s='hello|world|nice|to|meet|you'
perl -pe 's/^((?:[^|]*\|){3}[^|]*).*/$1/' <<< "$s"
正则表达式详细信息:
^:开始
:启动捕获组1
?::启动非捕获组
[^ |]*:匹配0个或更多非管道字符
\|:配管
{3} :结束非捕获组。{3} 匹配该组的3次重复
[^ |]*:匹配0个或更多非管道字符
:结束捕获组`
*匹配所有内容直到结束
Perl代码:
您可以通过以下方式进行捕获:
您可以通过以下方式进行捕获:
要删除除前3个管道外的所有管道和周围文字,可以执行以下操作:
$txt=~s/^?:[^ |]*\\\\{3}[^ |]*\K.*\s 要删除除前3个管道外的所有管道和周围文字,可以执行以下操作:
$txt=~s/^?:[^ |]*\\\\{3}[^ |]*\K.*\s 您正在使用正则表达式:join |,split/\\\\\\\\/[0..3]是的,使用正则表达式拆分。您正在使用正则表达式:join |,split/\\\\\\\\\\\/[0..3]是的,使用正则表达式拆分。