【发布时间】:2020-07-18 14:04:42
【问题描述】:
我正在尝试通过嵌套字符“%”来拆分字符串,
例如我有这个字符串
"Welcome to %aaatext%, discount 50% and you'll get %bbbtext%, thanks"
在这种情况下,我期望的结果:
(0) [Welcome to ]
(1) [aaatext]
(2) [, discount 50% and you'll get ]
(3) [bbbtext]
(4) [, thanks]
我试过下面的代码
my @arr = split /\%.*text\%/, $str;
但结果远非预期:(
(0) [Welcome to ]
(1) [, thanks]
在这种情况下是否可以使用正则表达式进行拆分?
非常感谢。
【问题讨论】:
-
你的代码如何知道是提取
%aaatext%还是%aaatext%, discount 50%?计数%也无济于事,请考虑"Welcome to %aaatext%, discounts are 50% and 70% for silver and gold card holders, resp., and you'll get %bbbtext%, thanks"。您需要为%s 之间的字符串指定一个模式作为分隔符。 -
是的,为什么第二个想要的项目是
, discount 50% and you'll get而不是, discount 50? -
split /(%\w*text%)/?split /(%[^ %]*text%)/? -
在这种使用中,文字“%”不应该通过使用
%%进行转义吗? (假设 CMD.exe。)解析器可能会因为试图在 50% 中的 % 之后找到结尾 % 而中断。