0

认为,set s1 "some4number"

我想将其更改为 some5number。

我希望这会奏效:

regsub {(\d)(\S+)} $s1 "[expr \\1 + 1]\\2"

但它出错了。在 TCL 中执行此操作的理想方法是什么?

4

1 回答 1

2

Tcler's Wiki 有很多简洁的东西。其中之一

# There are times when looking at this I think that the abyss is staring back
proc regsub-eval {re string cmd} {
    subst [regsub $re [string map {[ \\[ ] \\] $ \\$ \\ \\\\} $string] \[$cmd\]]
}

有了它,我们可以这样做:

set s1 "some4number"
# Note: RE changed to use forward lookahead
set s2 [regsub-eval {\d(?=\S+)} $s1 {expr & + 1}]
# ==> some5number

但这在 8.7(开发中)的未来会变得不那么糟糕。以下是您对apply-term 助手所做的操作:

set s2 [regsub -command {(\d)(\S+)} $s1 {apply {{- 1 2} {
    return "[expr {$1 + 1}]$2"
}}}]

使用辅助程序代替:

proc incrValueHelper {- 1 2} {
    return "[expr {$1 + 1}]$2"
}
set s2 [regsub -command {(\d)(\S+)} $s1 incrValueHelper]
于 2017-07-06T10:49:50.477 回答