Tcl regexp:为什么“+”不匹配尽可能多的?
Tcl regexp : Why '+' does not match as many as possible?
我用的是TCL8.4。在下面的表达式中,我尝试使用 ([0-9]+) 获取数值。但它并没有尽可能多地匹配,尽管手册页显示“+”意味着尽可能多地匹配(参考:http://wiki.tcl.tk/396)
另外,请share/suggest任何更好的方法来做我想做的事情。
%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]+?)
,它匹配一个或多个数字,但尽可能少 return 有效匹配。 模式末尾的所有惰性子模式仅匹配零个 (*?
) 或一个 (+?
) 个符号。
一个简单的解决方案就是添加一个尾随字符,这里是一个换行符(或空格):
regexp {NOTPLD STATS:(.*?)Packets:[\s]+([0-9]+)\s} $a t1 t2 c
^
如果值可以在字符串的末尾,则使用交替 (?:\s|$)
。
我用的是TCL8.4。在下面的表达式中,我尝试使用 ([0-9]+) 获取数值。但它并没有尽可能多地匹配,尽管手册页显示“+”意味着尽可能多地匹配(参考:http://wiki.tcl.tk/396) 另外,请share/suggest任何更好的方法来做我想做的事情。
%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]+?)
,它匹配一个或多个数字,但尽可能少 return 有效匹配。 模式末尾的所有惰性子模式仅匹配零个 (*?
) 或一个 (+?
) 个符号。
一个简单的解决方案就是添加一个尾随字符,这里是一个换行符(或空格):
regexp {NOTPLD STATS:(.*?)Packets:[\s]+([0-9]+)\s} $a t1 t2 c
^
如果值可以在字符串的末尾,则使用交替 (?:\s|$)
。