问题
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