Tcl 如何搜索列表中最后一个匹配的正则表达式

Tcl 如何搜索列表中最后一个匹配的正则表达式,tcl,expect,Tcl,Expect,我正试图找到一种方法来查找列表中第一个和最后一个匹配的单词或正则表达式 比如: set list "The dog rant to the field by the red house..." set first [lsearch -regexp $list \[Tt\]he] ($first =0) set last [lsearch -last -regexp $list \[Tt\]he ($last=7) 由于正则表达式可能非常慢,因此最好只执行一次正则表达式,而不是多次搜索目标行

我正试图找到一种方法来查找列表中第一个和最后一个匹配的单词或正则表达式

比如:

set list "The dog rant to the field by the red house..."

set first [lsearch -regexp $list \[Tt\]he] 
($first =0)
set last [lsearch -last -regexp $list \[Tt\]he
($last=7)

由于正则表达式可能非常慢,因此最好只执行一次正则表达式,而不是多次搜索目标行

   set list "The dog rant to the field by the red house..."
   set matches [regexp -inline -all {[Tt]he} $list]
   set first [lindex $matches 0]
   set last [lindex $matches end]
如果需要将索引放入匹配项所在的$list中,请使用
-索引
选项

  set matches [regexp -indices -inline -all {[Tt]he} $list]
参考资料:


除非您想特别排除大写字母h或e(或查找单词边界),否则此字母相当于大写字母h或e,速度大约快四倍。

根据实际数据的长度和匹配项的分布,可能最容易在反向列表上搜索并转换:

set ridx [lsearch -regexp [lreverse $list] {[Tt]he}]
set last [expr {[llength $list] - 1 - $ridx}]

Peter,我使用了“the”,但我需要regexp作为我的真实示例。也就是说,你的例子逻辑对我来说非常有效!非常感谢。我不知道有一个lreverse函数!那肯定会派上用场的!非常感谢。
set ridx [lsearch -regexp [lreverse $list] {[Tt]he}]
set last [expr {[llength $list] - 1 - $ridx}]