如何使用正则表达式仅提取两个字段
How to extract only two fields using Regular Expression
在 TCL 中,我正在为以下输出编写正则表达式:
输出参数是
packet-filter 0
identifier 0
direction bidirectional
network-ip 10.7.98.231/32
ue-port-start 0
ue-port-end 0
nw-port-start 0
nw-port-end 0
protocol 1
precedence 0
packet-filter 1
identifier 1
direction uplink
network-ip 10.7.98.231/32
ue-port-start 0
ue-port-end 0
nw-port-start 0
nw-port-end 0
protocol 1
precedence 0
我的正则表达式的输出:regexp -all -inline {direction\s+(\S+)} $args
是
{direction bidirectional} bidirectional {direction uplink} uplink
我需要提取方向值 bidirectional
和 uplink
有什么建议吗?
对于当前情况,捕获的子字符串是非空白文本块,如果每个项目的长度设置为 1
:
,您可以重新构建输出检查
set results [regexp -all -inline {direction\s+(\S+)} $args]
set res {}
foreach item $results {
if {[llength $item] == 1} {
lappend res $item
}
}
那么,$res
将只保留 bidirectional
和 uplink
。
参见Tcl demo。
对于更通用的情况,您可以使用
set res {}
foreach {whole capture1} $results {
lappend res $capture1
}
您可以添加更多 captureX
个参数来容纳您的正则表达式返回的所有捕获组值。
您只需要一个循环或类似的东西。如果你需要单独处理每个方向,foreach 循环是合适的:
set results [regexp -all -inline {direction\s+(\S+)} $args]
foreach {main sub} $results {
puts $sub
}
# bidirectional
# uplink
或者,如果您需要路线列表,那么 lmap
听起来很合适:
set directions [lmap {main sub} $results {set sub}]
# bidirectional uplink
regexp
不是必须的,你可以把args
的值处理成字典:
set d [dict create]
foreach {k v} $args {
dict lappend d $k $v
}
puts [dict get $d direction]
在 TCL 中,我正在为以下输出编写正则表达式:
输出参数是
packet-filter 0
identifier 0
direction bidirectional
network-ip 10.7.98.231/32
ue-port-start 0
ue-port-end 0
nw-port-start 0
nw-port-end 0
protocol 1
precedence 0
packet-filter 1
identifier 1
direction uplink
network-ip 10.7.98.231/32
ue-port-start 0
ue-port-end 0
nw-port-start 0
nw-port-end 0
protocol 1
precedence 0
我的正则表达式的输出:regexp -all -inline {direction\s+(\S+)} $args
是
{direction bidirectional} bidirectional {direction uplink} uplink
我需要提取方向值 bidirectional
和 uplink
有什么建议吗?
对于当前情况,捕获的子字符串是非空白文本块,如果每个项目的长度设置为 1
:
set results [regexp -all -inline {direction\s+(\S+)} $args]
set res {}
foreach item $results {
if {[llength $item] == 1} {
lappend res $item
}
}
那么,$res
将只保留 bidirectional
和 uplink
。
参见Tcl demo。
对于更通用的情况,您可以使用
set res {}
foreach {whole capture1} $results {
lappend res $capture1
}
您可以添加更多 captureX
个参数来容纳您的正则表达式返回的所有捕获组值。
您只需要一个循环或类似的东西。如果你需要单独处理每个方向,foreach 循环是合适的:
set results [regexp -all -inline {direction\s+(\S+)} $args]
foreach {main sub} $results {
puts $sub
}
# bidirectional
# uplink
或者,如果您需要路线列表,那么 lmap
听起来很合适:
set directions [lmap {main sub} $results {set sub}]
# bidirectional uplink
regexp
不是必须的,你可以把args
的值处理成字典:
set d [dict create]
foreach {k v} $args {
dict lappend d $k $v
}
puts [dict get $d direction]