reclx中的tcl list index [英] tcl list index in regexp
问题描述
有没有办法在正则表达式中使用列表索引?
Is there a way to use the list index in a regexp ?
我已尝试过这个但它不起作用:
I've tried with this but it doesn't work :
if {[regexp {.*\[lindex $mylist 2\].*} $mystring]} {
puts "OK"
}
位于名单mylist列表的索引2处的值未被替换在正则表达式。
the value located at list index 2 of the list named mylist is not replaced in the regexp.
谢谢。
推荐答案
如果你只是想要要查看另一个简短字符串是否存在, regexp
是不正确的方法。相反,首先使用字符串
:
If you just want to see if some short simple string is present in another, regexp
is not the right approach. Instead, use string first
:
if {[string first [lindex $mylist 2] $mystring] >= 0} {
puts "OK"
}
如果列表的第三个元素中确实有正则表达式,那么这就足够了,因为Tcl总是检测到RE是否匹配任何地方(默认情况下它的模式是非锚定的):
If the list really has a regular expression in its third element, then it's enough to do this because Tcl always detects if an RE matches anywhere (it's patterns are unanchored by default):
if {[regexp -- [lindex $mylist 2] $mystring]} {
puts "OK"
}
-
以防止RE以 -
字符,可能会导致混淆。您还可以使用 regexp
来使用类似字符串的第一个
食谱:
The --
is just in case the RE starts with a -
character, which can cause confusion. You could also use regexp
to work a bit like that string first
recipe:
if {[regexp ***=[lindex $mylist 2] $mystring]} {
但是字符串优先
的代码会更快!如果你想要比这更复杂的东西,那么停止并思考你所做的是否是正确的方法可能是一个好主意;当一个人发现自己在正则表达式中进行复杂的替换时,通常会陷入混乱。 (或者至少当我知道我需要重新考虑时。)在这里询问 - 同时提供更多的背景 - 可以帮助你解决问题。
But the code with string first
will be faster! If you want anything much more complicated than this, it's probably a good idea to stop and think whether what you're doing is the right approach; when one finds oneself doing complicated substitutions in regular expressions, one is usually getting into a mess. (Or at least that's when I know I need to rethink.) Asking here — while providing a bit more context — can help you figure things out.
这篇关于reclx中的tcl list index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!