Regex Perl正则表达式:在百分比字符内拆分%&引用;
我正在尝试通过嵌套字符“%”拆分字符串 例如,我有这个字符串Regex Perl正则表达式:在百分比字符内拆分%&引用;,regex,string,perl,split,Regex,String,Perl,Split,我正在尝试通过嵌套字符“%”拆分字符串 例如,我有这个字符串 “欢迎使用%aaatext%,折扣50%,您将获得%bbbtext%,谢谢” 在这种情况下,我预期的结果是: (0) [Welcome to ] (1) [aaatext] (2) [, discount 50% and you'll get ] (3) [bbbtext] (4) [, thanks] 我尝试了以下代码 my @arr = split /\%.*text\%/, $str; 但结果与预期相差甚远:( 在这种情况下
“欢迎使用%aaatext%,折扣50%,您将获得%bbbtext%,谢谢”
在这种情况下,我预期的结果是:
(0) [Welcome to ]
(1) [aaatext]
(2) [, discount 50% and you'll get ]
(3) [bbbtext]
(4) [, thanks]
我尝试了以下代码
my @arr = split /\%.*text\%/, $str;
但结果与预期相差甚远:(
在这种情况下,是否可以使用正则表达式进行拆分
非常感谢。试试这个Perl一行程序:
% cat > input_file <<EOF
Welcome to %aaatext%, discount 50% and you'll get %bbbtext%, thanks
EOF
% perl -lne 'print for split m{ % ( \w* text ) % }x, $_;' input_file
Welcome to
aaatext
, discount 50% and you'll get
bbbtext
, thanks
<代码> %CAT>输入文件,您的代码是如何知道是否提取“代码> %AATTXT %< /代码>或<代码> %AAtExt%,折扣50% < /代码>计数>代码> %>代码>对您也没有帮助,请考虑<代码>“欢迎访问%AAtExt%,折扣为银和金卡持有者的50%和70%,您将得到%BBBTEX%,谢谢”。您需要为
%
之间的字符串指定一个模式作为分隔符。是的,为什么第二个所需项目,折扣50%,您将得到,而不是,折扣50
?拆分/(\w*text%)/
?拆分/([^%]*text%)/
?不是文字“%”在这种情况下,应该通过使用%%
?(假设为CMD.exe)进行转义。由于试图在50%中的%之后找到结尾%,解析器可能会中断。
% cat > input_file <<EOF
Welcome to %aaatext%, discount 50% and you'll get %bbbtext%, thanks
EOF
% perl -lne 'print for split m{ % ( \w* text ) % }x, $_;' input_file
Welcome to
aaatext
, discount 50% and you'll get
bbbtext
, thanks