2017-03-09 31 views
0

我想查找某個文件中是否存在If塊。Tcl [regexp]:表達式匹配,如果塊內有變量

我有一個文件new.tcl如下:

if { [info exists var1] } { 
    if { "$var1" == "val1" } { 
    puts "var1 has value as val1" 
    } 
} else { 
    puts "var1 does not exists" 
} 

我讀在另一個Tcl的功能此文件並試圖以匹配通過如果功能regexp和值以及變量塊此功能所用是變量。

我實現文件的樣子,

set valueDict [list 'var1' 'val1'] 
set valDictLen [llength $valueDict] 
set myFilePtr [open "new.tcl" "r"] 
set myFileContent [read $myFilePtr] 
close $myFilePtr 

for { set index 0 } { $index < $valDictLen } { incr index 2 } { 
    set currVar [lindex $valueDict $index] 
    set currVal [lindex $valueDict [expr $index + 1]] 

    # I actually want to match the entire if block content here 
    if { ![regexp "if \{ \[info exists $currVal\] \}" $myFileContent] } { 
    puts "Code not present" 
    } 
} 
+1

如果代碼格式很好,你可以使用正則表達式,如[\(?:\ n | ^)\ s *?{\ s *?\ [info exists var1 \ s *?] \ s *? } \ S * {* \ n}(?:??\ N | $)'](https://regex101.com/r/PUpBvb/1)(未在Tcl中測試過),但我懷疑它在任何情況下都能正常工作。用正則表達式解析代碼通常是一個壞主意。 –

+0

請注意我想在正則表達式中使用變量'$ currVal'而不是'var1'直接使用 – Ashwin

+0

看看這個答案並告訴我它是否解決了你的問題:http://stackoverflow.com/questions/14237376 /如何使用正則表達式匹配一個圓括號在TCL – user2141046

回答

-1

嘗試:

if { ![regexp "if *{ *[info exists $currVal] *}" $myFileContent] } { 
    puts "Code not present" 
} 

當您在TCL正則表達式使用「,使用[機構的指令/關鍵字應遵循

+0

Hi Bordoloi,此解決方案不起作用。它實際上是評估表達式並用正則表達式 – Ashwin

+0

中的值代替哪個tcl版本使用? –

+0

我正在使用Tcl 8.5.7 – Ashwin

-1
SBORDOLO-M-V1VG:Downloads sbordolo$ cat t3 

set var1 "value" 
set currVal "var1" 
#set myFileContent "\[info exists var1\]" 
set myFileContent {[info exists var1]} 

if { ![regexp "[info exists $currVal]" $myFileContent] } { 
    puts "Code not present" 
} else { 
    puts "Code present" 
} 
SBORDOLO-M-V1VG:Downloads sbordolo$ 
SBORDOLO-M-V1VG:Downloads sbordolo$ tclsh t3 
Code present 
SBORDOLO-M-V1VG:Downloads sbordolo$ 
+0

您的代碼巧合工作。模式字符串的計算結果爲1,因此它匹配任何包含至少一個1個字符的字符串。爲什麼不使用模式「info exists $ currVal」? –

+0

請添加puts $ myFileContent。它仍然打印字符串,而不是評估的字符。注意我已經使用了{} not「」 –

+0

我正在討論* pattern *,即''[info exists $ currVal]「'。當調用'regexp'命令時,它的計算結果爲1,這意味着真正的命令行是'regexp 1 [info exists var1]'。 –

相關問題