Tcl正则表达式-复制所有匹配到列表



我试图使用简单的代码从看起来像这样的文本文件中找到匹配| 259.937 MB/s|我只要求数字部分。我已经测试了正则表达式使用在线正则表达式调试器,它似乎工作,但当我测试出来,我没有得到任何打印在列表

set fp [open "logfile.log" r]
set bandwidth [regex -inline {(d{3}.d{3})sMB/s|}  $fp -> bandwidth]
puts "The contents of the list is: $bandwidth"
close $fp

我也不确定列表是否是嵌入列表中的列表,这意味着外部列表包含匹配,内部列表包含每个匹配的总和子匹配。但是如果可能的话,我更愿意只使用sub match。

您遇到的问题是,您将子匹配变量-inline选项一起使用,这可能应该是一个错误的组合。相反,这样做(不含-inline):

if {[regex {(d{3}.d{3})sMB/s|}  $fp -> bandwidth]} {
puts "The contents of the list is: $bandwidth"
} else {
puts "Nothing was found"
}

或此(-all以及-inline):

set matches [regex -all -inline {(d{3}.d{3})sMB/s|} $fp]
if {[llength $matches]} {
puts "The full contents of the list is: $matches"
foreach {-> bandwidth} $matches {
puts "Found $bandwidth"
}
}

您匹配的是文件句柄,而不是文件内容

使用这些数据:

$ cat logfile.log
a | b | 123.456 MB/s| c
d | e | 789.012 MB/s| f

将整个文件读入一个变量并使用[regexp -all]

进行搜索
set fp [open logfile.log]
set data [read $fp]
close $fp
# this one uses a lookahead and no capturing parentheses
# which makes the "-inline" list contain only the wanted data
regexp -all -inline {d{3}.d{3}(?= MB/s|)} $data
# => {123.456 789.012}

或遍历文件的行。

set fp [open "logfile.log" r]
while {[gets $fp line] != -1} {
if {[regex {(d{3}.d{3})sMB/s|}  $line -> bandwidth]} {
lappend found $bandwidth
}
}
close $fp
puts $found  ;# => 123.456 789.012

最新更新