2017-07-06 113 views
0

假設,set s1 "some4number"如何在TCL的regsub中使用expr?

我想將其更改爲some5number。

我希望這會工作:

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

但它的錯誤了。在TCL中這樣做的理想方式是什麼?

+0

我在我的手機現在,所以我不能回答正確,但「這是煩人的複雜「是總結。除非你有Tcl 8.7,我在'regsub'中添加了'-command'選項,但是它仍處於check-out-source-control-only狀態。 –

回答

2

Tcler's 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 + 1}]$2" 
}}}] 

在一名助手,而不是程序:

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