问题
when I am using the while loop to match a variable using regexp I want the matched variable to form a list by using lappend. The code is
set file_name [open filename.txt r]
set newlist [list]
while {[gets $file_name line] >= 0} {
regexp {cell \(\"(.*)\"} $line match cell_name
if {[info exists cell_name] && $cell_name != ""} {
puts "$cell_name"
lappend $newlist $cell_name
unset cell_name
}
}
foreach item $newlist {puts $item}
close $file_name
The text which it is matching is like cell ("aabbcc") where the values inside the quotes are changing. The values are getting captured by this code but it is not creating a list after appending. I need all the values as a list. Can u pls tell me where I am going wrong.
回答1:
A $ too much.
Change the line
lappend $newlist $cell_name_matched
to
lappend newlist $cell_name_matched
Otherwise you find the result in ${}.
You should also check if you regexp finds something:
if {[regexp {cell \(\"(.*)\"} $line match cell_name_matched]} {
puts "$cell_name_matched"
lappend newlist $cell_name_matched
}
The unset will probably throw an error too, leave it alone and remove it.
来源:https://stackoverflow.com/questions/17559577/how-to-do-lappend-in-a-while-loop-using-regexp