将数字与 TCL 中的特定模式匹配



我有这样的文本:

文本 ="已传输 56 个 IPv4 数据包和传输 20 个 IPv6 数据包">

从这种模式中,我想在tcl 中使用正则表达式提取 56 和 20。

但是我的实现也提取了 4(来自 ipv4(和 6(来自 ipv6(。

[regexp -inline -all {d+} $text]

有人可以在这里帮忙吗?

您可以使用yd+ymd+M将数字作为整个单词进行匹配,当它们既不粘在字母、数字或下划线上:

set text {56 ipv4 packets transmitted and 20 ipv6 packets transmitted}
set results [regexp -inline -all {yd+y} $text]
puts $results
# => 56 20
set results2 [regexp -inline -all {md+M} $text]
puts $results2
# => 56 20

请参阅 Tcl 演示。

请参阅 Tcl 文档:


       m仅在单词
的开头匹配M
       仅在单词
的末尾匹配y
       仅在单词
的开头或结尾匹配

set text {56 ipv4 packets transmitted and 20 ipv6 packets transmitted}
set nums [lmap word [split $text] {
if {[string is integer -strict $word]} then {set word} else continue
}]
56 20

最新更新