如何使用正则表达式在while循环中执行lappend [英] How to do lappend in a while loop using regexp

查看:28
本文介绍了如何使用正则表达式在while循环中执行lappend的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 while 循环使用正则表达式匹配变量时,我希望匹配的变量使用 lappend 形成一个列表.代码是

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    

它匹配的文本就像单元格(aabbcc"),其中引号内的值正在改变.此代码正在捕获这些值,但在附加后它不会创建列表.我需要所有值作为列表.你能告诉我我哪里出错了.

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.

推荐答案

$ 太多了.

换行

lappend $newlist $cell_name_matched

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
}

unset 也可能会抛出一个错误,不管它并删除它.

The unset will probably throw an error too, leave it alone and remove it.

这篇关于如何使用正则表达式在while循环中执行lappend的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆