Trying to match a text using regexp and foreach

别等时光非礼了梦想. 提交于 2019-12-25 07:31:33

问题


I am using the following code to match a text like cell ("acf12bcjd6"). The values inside the quotes keep changing and I have to capture all of them. The code I used is:

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

But I am getting an error saying "can't reach match, no such variable". I do not understand my mistake. Am I doing it correct?


回答1:


Your program is failing because the regexp pattern isn't matching the string, so match isn't being set. Try this

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

The pattern assumes that the space between cell and the opening bracket is optional. I also assume you want the quotation marks stripped away.




回答2:


Try to use this instead:

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


来源:https://stackoverflow.com/questions/17436835/trying-to-match-a-text-using-regexp-and-foreach

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