How to do lappend in a while loop using regexp

天大地大妈咪最大 提交于 2020-01-25 03:09:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!