gpt4 book ai didi

regex - Tcl 正则表达式 : Why '+' does not match as many as possible?

转载 作者:行者123 更新时间:2023-12-04 08:18:06 25 4
gpt4 key购买 nike

我正在使用 TCL8.4。在下面的表达式中,我尝试使用 ([0-9]+) 获取数值。但是它没有尽可能多地匹配,尽管手册页显示“+”是为了匹配尽可能多的(引用:http://wiki.tcl.tk/396)
另外,请分享/建议任何更好的方式来做我想做的事情。

%set a {
NOTPLD STATS:
Bps: 0; pps: 0; Bytes: 0; Packets: 4535

TPLD STATS:
Bps: 0; pps: 0; Bytes: 0; Packets: 4535

}
%
% regexp {NOTPLD STATS:(.*?)Packets:[\s]+([0-9]+)} $a t1 t2 c
1
% set c
4

最佳答案

Interaction Between Quantifiers with Different Greediness :

All quantifiers in a branch get switched to the same greediness, so adding a non-greedy quantifier makes the other quantifiers in the branch implicitly non-greedy as well.



因此,您的 ([0-9]+)被解释为 ([0-9]+?) , 它匹配一位或多位数字,但尽可能少地返回有效匹配。 模式末尾的所有惰性子模式仅匹配零 ( *? ) 或一个 ( +? ) 符号。

一个简单的解决方案是添加一个尾随字符,在这里,它是一个换行符(或空格):
regexp {NOTPLD STATS:(.*?)Packets:[\s]+([0-9]+)\s} $a t1 t2 c
^

IDEONE demo

如果该值可以位于字符串的末尾,请使用替代 (?:\s|$) .

关于regex - Tcl 正则表达式 : Why '+' does not match as many as possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34222154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com