space 缺失时使用正则表达式提取值
Extract value using regex when space is missing
我正在尝试从下面的输出中提取文本和第三列。我的问题是有一行缺少 space。在这种情况下是否可以提取该值?
4086 process-working 841901 841901 1234 22
4297 procesor_stats_controller_fmm543182 543182 0 22
4028 ipv6_ma 3063025 3063025 -55 78
4280 tty-verifyd 694043 694043 0 22
到目前为止,我的正则表达式如下所示:
\d+\s+(\w+-?\w+)\s*\d+\s+\d+\s+(-?\d+)\s+\d+
谢谢
编辑:这实际上是设备中的一个错误,至少应该有一个 space,所以我会让他们修复它然后重试。感谢您花时间回答这个问题:)
在这种情况下,我首先将行拆分为字段
foreach line $lines {
set fields [regexp -inline -all {\S+} $line]
if {[llength $fields] == 6} {
puts [lindex $fields 2]
} else {
# extract the digits at the end of this field
regexp {\d+$} [lindex $fields 1] value
puts $value
}
}
841901
543182
3063025
694043
问题出在 \w
。 \w
等同于 [a-zA-Z0-9_]
。
因此,它也会与数字匹配(因为缺少 space)。
而不是 \w
,使用 [a-zA-Z_]
。因此,这个正则表达式应该适合你:
\d+\s+([a-z]+-?[a-z]+)\s*(\d+)\s+\d+\s+\d+\s+\d+
我正在尝试从下面的输出中提取文本和第三列。我的问题是有一行缺少 space。在这种情况下是否可以提取该值?
4086 process-working 841901 841901 1234 22
4297 procesor_stats_controller_fmm543182 543182 0 22
4028 ipv6_ma 3063025 3063025 -55 78
4280 tty-verifyd 694043 694043 0 22
到目前为止,我的正则表达式如下所示:
\d+\s+(\w+-?\w+)\s*\d+\s+\d+\s+(-?\d+)\s+\d+
谢谢
编辑:这实际上是设备中的一个错误,至少应该有一个 space,所以我会让他们修复它然后重试。感谢您花时间回答这个问题:)
在这种情况下,我首先将行拆分为字段
foreach line $lines {
set fields [regexp -inline -all {\S+} $line]
if {[llength $fields] == 6} {
puts [lindex $fields 2]
} else {
# extract the digits at the end of this field
regexp {\d+$} [lindex $fields 1] value
puts $value
}
}
841901
543182
3063025
694043
问题出在 \w
。 \w
等同于 [a-zA-Z0-9_]
。
因此,它也会与数字匹配(因为缺少 space)。
而不是 \w
,使用 [a-zA-Z_]
。因此,这个正则表达式应该适合你:
\d+\s+([a-z]+-?[a-z]+)\s*(\d+)\s+\d+\s+\d+\s+\d+