如何使用foreach使用正则表达式 [英] How to use foreach for using regexp
问题描述
我正在使用下面的代码来搜索特定的数据并将其存储在一个变量中。
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
这里的名字是有很多数据的变量。我得到一个错误说:错误:无效的命令名称1。
我是tcl的新手,所以我无法弄清楚什么是错的。是我的代码是否正确,它的工作?谢谢
您的正则表达式正在评估第一个和 regexp {[cell] +} $ search match
返回
1
,然后变成:
[ 1]
这是一个无效的命令,删除方括号:
regexp {[cell] +} $ search match
现在,我不认为你正确地使用正则表达式,它会查找任何组合 c
, e 和
l
至少一次,意味着它会接受 cell
, lec
甚至是 c
你可能想要:
regexp {((?:cell)+)} $匹配的匹配
这将匹配 cell
, cellcell
, cellcellcell
等等,并把它存储在变量匹配
中。
括号用于捕获匹配的组;这些(?: ...)
是用于非捕获组的。
编辑:
set newlist [list]
foreach搜索$ names {
regexp {cell \s * \(([^] +)\)} $ search匹配
lappend $ newlist $匹配
}
现在,$ newlist列表包含所有匹配的值,您可以执行foreach显示所有他们;
foreach n $ newlist {puts $ n}
I am using the following code to search for a particular data and store it in a variable.
foreach searched $names {
[regexp {[cell]+} $searched match]
}
Here names is the variable which has many data. I am getting an error saying: Error: invalid command name "1.
I am new to tcl so I cant figure out whats wrong. Is my code correct, will it work? Thanks
Your regexp is evaluating first and regexp {[cell]+} $searched match
returns 1
, which then becomes:
[1]
Which is an invalid command. Remove the square brackets:
regexp {[cell]+} $searched match
Now, I don't think you're using the regexp correctly. This will look for any of the combinations c
, e
and l
at least one time, meaning it'll accept cell
, lec
or even c
alone. You probably want:
regexp {((?:cell)+)} $searched match matched
This will match cell
, cellcell
, cellcellcell
and so on and store it in the variable matched
.
Brackets are used to capture matching groups; and these (?: ...)
are for non capturing groups.
EDIT: Following on my comment, I would do something like:
set newlist [list]
foreach searched $names {
regexp {cell\s*\("([^"]+)"\)} $searched match matched
lappend $newlist $matched
}
Now, the list $newlist contains all the matched values. You can do a foreach to display all of them;
foreach n $newlist {puts $n}
这篇关于如何使用foreach使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!