如何在 TCL 的 regsub 中使用 expr?
How to use expr inside regsub in TCL?
假设,set s1 "some4number"
我想改成5号。
我希望这会奏效:
regsub {(\d)(\S+)} $s1 "[expr \1 + 1]\2"
但是出错了。在 TCL 中执行此操作的理想方法是什么?
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
-term 助手所做的事情:
set s2 [regsub -command {(\d)(\S+)} $s1 {apply {{- 1 2} {
return "[expr { + 1}]"
}}}]
改用辅助程序:
proc incrValueHelper {- 1 2} {
return "[expr { + 1}]"
}
set s2 [regsub -command {(\d)(\S+)} $s1 incrValueHelper]
假设,set s1 "some4number"
我想改成5号。
我希望这会奏效:
regsub {(\d)(\S+)} $s1 "[expr \1 + 1]\2"
但是出错了。在 TCL 中执行此操作的理想方法是什么?
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
-term 助手所做的事情:
set s2 [regsub -command {(\d)(\S+)} $s1 {apply {{- 1 2} {
return "[expr { + 1}]"
}}}]
改用辅助程序:
proc incrValueHelper {- 1 2} {
return "[expr { + 1}]"
}
set s2 [regsub -command {(\d)(\S+)} $s1 incrValueHelper]