gpt4 book ai didi

regex - Tclsh : How to get the first occurence of the string by regexp?

转载 作者:行者123 更新时间:2023-12-02 01:55:34 25 4
gpt4 key购买 nike

我有一个具有多次出现模式的字符串。我需要从字符串中提取第一个模式。

即:

我的模式:

ABC : 1
XXX : 3
YYY : 4
ZZZ : 9

ABC : 3
XXX : 4
YYY : 6
ZZZ : 7

我想根据为 ABC 值提供的值提取 block 。如果我将 ABC 值设为 1,则输出应为:

ABC : 1
XXX : 3
YYY : 4
ZZZ : 9

我试过了,

set ABCVal 1

regexp "ABC\[ \]+:\[ \]+$ABCVal(.*)\[^ABC\]" $buffer

这匹配整个缓冲区。

最佳答案

我会首先将文本拆分为空行分隔的单元,然后在该列表中搜索模式:

set text {ABC : 1
XXX : 3
YYY : 4
ZZZ : 9

ABC : 3
XXX : 4
YYY : 6
ZZZ : 7}
package require textutil::split
set blocks [textutil::split::splitx $text {\n{2,}}]
set abc 3
set index [lsearch -regexp $blocks "^ABC : $abc\\y"]
puts [lindex $blocks $index]
ABC : 3
XXX : 4
YYY : 6
ZZZ : 7

我使用正则表达式 \y 断言,因此“^ABC : 3”与文本“ABC : 345”不匹配

关于regex - Tclsh : How to get the first occurence of the string by regexp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com