尝试使用正则表达式和foreach匹配文本

时间:2013-07-02 22:25:46

标签: regex tcl

我使用以下代码来匹配cell ("acf12bcjd6")这样的文字。引号内的值不断变化,我必须捕获所有这些值。我使用的代码是:

foreach searched_data $final {   
    [regexp {cell\(.*\)+} $searched_data match]   
    puts "$match"   
}

但我收到的错误是“无法达到匹配,没有这样的变量”。我不明白我的错误。我做得对吗?

2 个答案:

答案 0 :(得分:1)

您的程序失败,因为正则表达式模式与字符串不匹配,因此未设置match。试试这个

foreach searched_data $final {
    if {[regexp {cell +\(\"(.*)\"\)} $searched_data junk match]} {
        puts stdout $match
    }
}

该模式假设cell和左括号之间的空格是可选的。我还假设您希望剥离引号。

答案 1 :(得分:0)

尝试使用此代码:

foreach searched_data $final {   
    set match [regexp {cell ?\([^)]*\)} $searched_data]   
    puts "$match"   
}