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

match number with specific pattern in tcl

我有这样一条短信:

text = "传输了 56 个 ipv4 数据包和传输了 20 个 ipv6 数据包"

我想从这个模式中提取 56 和 20 使用 regexp in tcl.

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

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

有人可以帮忙吗?

您可以使用 \y\d+\y\m\d+\M 将数字作为整个单词进行匹配,前提是数字不与字母、数字或下划线相连:

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

参见Tcl demo

Tcl docs:

\m
       matches only at the beginning of a word
\M
       matches only at the end of a word
\y
       matches only at the beginning or end of a word

或者

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