假设set s1 "some4number"
我想将它改为some5number。
我希望这会奏效:
regsub {(\d)(\S+)} $s1 "[expr \\1 + 1]\\2"
但它出错了。在TCL中这样做的理想方法是什么?
答案 0 :(得分:2)
Tcler的Wiki有许多巧妙的东西。其中一个是this:
# 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
期限助手所做的事情:
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]