TCL中的子串提取
Substring extraction in TCL
我正在尝试从 TCL 中的字符串中提取一系列字符。
说,我有 "blahABC:blahDEF:yadamsg=abcd"
。
我想提取以 "msg="
开头的子字符串,直到到达字符串的末尾。
或者更确切地说,我有兴趣从上面的示例字符串中提取 "abcd"
。
非常感谢任何帮助。
谢谢。
正则表达式是完成这类任务的工具。
Tcl 中的一般语法是:
regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
您的任务的一个简单解决方案是:
set string blahblah&msg=abcd&yada
# match pattern for a =, 0-n characters which are not an & and one &. The grouping with {} is necessary due to special charactaer clash between tcl and re_syntax
set exp {=([^&]*)&}
# -> is an idiom. In principle it is the variable containing the whole match, which is thrown away and only the submatch is used
b
regexp $exp $string -> subMatch
set $subMatch
一个很好的工具来试验和玩正则表达式 ist Visual Regexp (http://laurent.riesterer.free.fr/regexp/)。我建议下载并开始播放。
相关的手册页是 re_syntax、regexp 和 regsub
约阿希姆
另一种方法:以&
为分隔符拆分查询参数,找到以"msg="开头的元素,然后得到=
之后的文本
% set string blahblah&msg=abcd&yada
blahblah&msg=abcd&yada
% lsearch -inline [split $string &] {msg=*}
msg=abcd
% string range [lsearch -inline [split $string &] {msg=*}] 4 end
abcd
代码
proc value_of {key matches} {
set index [lsearch $matches "yadamsg"]
if {$index != -1} {
return [lindex $matches $index+1]
}
return ""
}
set x "blahABC:blahDEF:yadamsg=abcd:blahGHI"
set matches [regexp -all -inline {([a-zA-Z]+)=([^:]*)} $x]
puts [value_of "yadamsg" $matches]
输出:
abcd
更新
不需要upvar。看评论。
我正在尝试从 TCL 中的字符串中提取一系列字符。
说,我有 "blahABC:blahDEF:yadamsg=abcd"
。
我想提取以 "msg="
开头的子字符串,直到到达字符串的末尾。
或者更确切地说,我有兴趣从上面的示例字符串中提取 "abcd"
。
非常感谢任何帮助。
谢谢。
正则表达式是完成这类任务的工具。 Tcl 中的一般语法是:
regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
您的任务的一个简单解决方案是:
set string blahblah&msg=abcd&yada
# match pattern for a =, 0-n characters which are not an & and one &. The grouping with {} is necessary due to special charactaer clash between tcl and re_syntax
set exp {=([^&]*)&}
# -> is an idiom. In principle it is the variable containing the whole match, which is thrown away and only the submatch is used
b
regexp $exp $string -> subMatch
set $subMatch
一个很好的工具来试验和玩正则表达式 ist Visual Regexp (http://laurent.riesterer.free.fr/regexp/)。我建议下载并开始播放。
相关的手册页是 re_syntax、regexp 和 regsub
约阿希姆
另一种方法:以&
为分隔符拆分查询参数,找到以"msg="开头的元素,然后得到=
% set string blahblah&msg=abcd&yada
blahblah&msg=abcd&yada
% lsearch -inline [split $string &] {msg=*}
msg=abcd
% string range [lsearch -inline [split $string &] {msg=*}] 4 end
abcd
代码
proc value_of {key matches} {
set index [lsearch $matches "yadamsg"]
if {$index != -1} {
return [lindex $matches $index+1]
}
return ""
}
set x "blahABC:blahDEF:yadamsg=abcd:blahGHI"
set matches [regexp -all -inline {([a-zA-Z]+)=([^:]*)} $x]
puts [value_of "yadamsg" $matches]
输出:
abcd
更新 不需要upvar。看评论。