【问题标题】:Perl regex: split inside percent character "%"Perl Regex:拆分内部字符“%”
【发布时间】: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% 中的 % 之后找到结尾 % 而中断。

标签: regex string perl split


【解决方案1】:

试试这个 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

这里,
m{}x 是带有 x 修饰符的正则表达式,导致 Perl 忽略正则表达式中的空格和 cmets,以提高可读性,
\w* 是 0 个或多个单词字符,
% ( \w* text ) % 捕获以text 结尾的单词,两侧带有百分号,使split 也能返回这些单词。

【讨论】:

    猜你喜欢
    • 2013-07-07
    • 1970-01-01
    • 2015-06-18
    • 2015-02-07
    • 2013-11-08
    • 2012-07-30
    • 1970-01-01
    • 2013-01-23
    • 2015-07-09
    相关资源
    最近更新 更多