我使用以下代码搜索特定数据并将其存储在变量中。
foreach searched $names {
[regexp {[cell]+} $searched match]
}
这里的名称是包含许多数据的变量。我收到一个错误说:Error: invalid command name "1.
我是tcl的新手,所以我无法弄清楚什么是错的。我的代码是否正确,是否有效?谢谢
答案 0 :(得分:4)
您的正则表达式首先评估,regexp {[cell]+} $searched match
返回1
,然后变为:
[1]
这是一个无效的命令。删除方括号:
regexp {[cell]+} $searched match
现在,我认为您没有正确使用正则表达式。这将至少一次查找任何组合c
,e
和l
,这意味着它将接受cell
,lec
甚至{{ 1}}单独。你可能想要:
c
这将匹配regexp {((?:cell)+)} $searched match matched
,cell
,cellcell
等,并将其存储在变量cellcellcell
中。
括号用于捕捉匹配组;这些matched
适用于非捕获组。
编辑:关注我的评论,我会做类似的事情:
(?: ...)
现在,列表$ newlist包含所有匹配的值。你可以做一个foreach来显示所有这些;
set newlist [list]
foreach searched $names {
regexp {cell\s*\("([^"]+)"\)} $searched match matched
lappend $newlist $matched
}
答案 1 :(得分:1)
根据您的评论和Jerry的回答,我想您需要
regexp -- {(?:cell)\s+?(\("\w+"\))} $searched -> matched_part_in_brakets
puts $matched_part_in_brakets
或
regexp -- {(?:cell)\s+?(\("\w+"\))} $searched match matched_part_in_brakets
puts $matched_part_in_brakets