我必须从指定的字符串中获取模式
这是我第一次使用tcl。与perl一样,我只需使用$1
$2
... $n
获取分组值即可。在tcl我尝试过这种方式......实际上这甚至都没有工作......
while { [gets $LOG_FILE line] >= 0 } {
if {[regexp -inline {Getting available devices: (/.+$)} $line]} {
puts {group0}
}
}
答案 0 :(得分:2)
使用regexp
,您可以通过两种方式获取子匹配。
如果没有-inline
,您必须提供足以获得您关注的子匹配的变量(第一个变量适用于整个匹配区域,如Perl中的$&
):< / p>
if {[regexp {Getting available devices: (/.+$)} $line a b]} {
puts $b
}
将->
用作整体匹配变量非常常见。它对Tcl来说完全没有特殊性,但是它使脚本更容易理解:
if {[regexp {Getting available devices: (/.+$)} $line -> theDevices]} {
puts $theDevices
}
使用-inline
,regexp
会返回匹配的内容列表,而不是将它们分配给变量。
set matched [regexp -inline {Getting available devices: (/.+$)} $line]
if {[llength $matched]} {
set group1 [lindex $matched 1]
puts $group1
}
-inline
表单适用于多变量foreach
和lassign
,,特别是与-all
结合使用。
foreach {-> theDevices} [regexp -inline -all {Getting available devices: (/.+$)} $line] {
puts $theDevices
}