如何在列表中搜索最后匹配的正则表达式
How to lsearch for last matching regular expression in list
我正在尝试找到一种方法来查找列表中第一个和最后一个匹配的单词或正则表达式。
类似于:
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 中的索引,请使用
-indices
选项。
set matches [regexp -indices -inline -all {[Tt]he} $list]
参考文献:regexp
set res [lsearch -nocase -all $list the]
set first [lindex $res 0]
set last [lindex $res end]
除非您想特别排除大写字母 h 或 e(或寻找单词边界),否则这个是等效的,而且速度大约快四倍。
根据实际数据的长度和匹配的分布,在反向列表上进行搜索并转换可能是最简单的:
set ridx [lsearch -regexp [lreverse $list] {[Tt]he}]
set last [expr {[llength $list] - 1 - $ridx}]
我正在尝试找到一种方法来查找列表中第一个和最后一个匹配的单词或正则表达式。
类似于:
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 中的索引,请使用
-indices
选项。
set matches [regexp -indices -inline -all {[Tt]he} $list]
参考文献:regexp
set res [lsearch -nocase -all $list the]
set first [lindex $res 0]
set last [lindex $res end]
除非您想特别排除大写字母 h 或 e(或寻找单词边界),否则这个是等效的,而且速度大约快四倍。
根据实际数据的长度和匹配的分布,在反向列表上进行搜索并转换可能是最简单的:
set ridx [lsearch -regexp [lreverse $list] {[Tt]he}]
set last [expr {[llength $list] - 1 - $ridx}]