温馨提示:本文翻译自stackoverflow.com,查看原文请点击:regex - regular expression to select particular word when it is not followed by particular pattern?
awk regex ubuntu

regex - 在没有特定模式的情况下选择特定单词的正则表达式?

发布于 2020-04-07 11:46:12

我有以下格式的数据列表:

eth0: flags=73<UP,LOOPBACK,RUNNING>  mtu 1500
    inet 127.0.0.1  netmask 255.0.0.0
    inet6 ::1  prefixlen 128  scopeid 0xfe<compat,link,site,host>
    loop  (Local Loopback)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth1: flags=73<UP,LOOPBACK,RUNNING>  mtu 1500
    inet6 ::1  prefixlen 128  scopeid 0xfe<compat,link,site,host>
    loop  (Local Loopback)
    RX packets 0  bytes 0 (0.0 B)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 0  bytes 0 (0.0 B)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

我需要选择eth1(这是第一个单词,并且始终e是以开头的单词),其后没有127.0.0.1(也可能在下一行的后面出现)。

这里eth0不合格,因为后面跟着127.0.0.1

我尝试了一切,但似乎没有任何效果。正则表达式甚至可能吗?如果是,那怎么办?

查看更多

提问者
rahul Kushwaha
被浏览
77
MonkeyZeus 2020-02-01 04:28

不确定Ubuntu的实现细节,但可以使用否定的前瞻:

^eth\d+(?=:)(?!.*\n.*[^0-9]127\.0\.0\.1[^0-9])
  • ^eth\d+(?=:) -行的开头必须是“ eth”,后跟一个或多个数字,然后是冒号,但不要捕获冒号
  • (?!.*\n.*[^0-9]127\.0\.0\.1[^0-9]) -确保上一个匹配项之后的内容不包含“ 127.0.0.1”

https://regex101.com/r/NeEAnn/1