匹配字符串后也想打印下一行

want to print the next line also after matching the string

我有一个字符串

output = '''Gateway of last resort is not set

      10.0.1.0/8 is variably subnetted, 4 subnets, 2 masks
C        10.1.0.0/24 is directly connected, Ethernet1/0
L        10.1.0.1/32 is directly connected, Ethernet0/0
C        10.2.0.0/24 is directly connected, Ethernet0/1
L        19.18.2.1/32 is directly connected, Serial2/1
O     19.18.3.0/20 [110/128] via 19.18.2.2, 00:00:50, Serial1/1
                     [110/128] via 19.18.1.2, 00:00:50, Serial1/0

O     12.18.3.1/20 [110/128] via 19.18.2.2, 00:00:50, Serial1/1
                     [110/128] via 19.18.1.2, 00:00:50, Serial1/0

O     12.18.1.0/20 [110/128] via 19.18.2.2, 00:00:50, Serial0/1
                     [110/128] via 19.18.1.2, 00:00:50, Serial0/0'''

我从这个字符串匹配 O 并使用以下方法打印完整行:

regex = re.findall("O\s+(?P<O>\w+.\w+.\w+.\w+.*)", output, re.M)

它给我的输出为:

['19.18.3.0/20 [110/128] via 19.18.2.2, 00:00:50, Serial1/1', '12.18.3.1/20 [110/128] via 19.18.2.2, 00:00:50, Serial1/1', '12.18.1.0/20 [110/128] via 19.18.2.2, 00:00:50, Serial0/1']

但我想将这些行连同上面的输出一起打印出来。

[110/128] via 19.18.1.2, 00:00:50, Serial1/0,  [110/128] via 19.18.1.2, 00:00:50, Serial1/0, [110/128] via 19.18.1.2, 00:00:50, Serial0/0 

您可以选择匹配以模式后的空格开头的可选行:

O\s+(?P<O>\d+\.\d+\.\d+\.\d+.*(?:[\r\n]+[^\S\r\n]+.*)?)
                              ^^^^^^^^^^^^^^^^^^^^^^^^      

this regex demo

更新的模式详细信息:(?:[\r\n]+[^\S\r\n]+.*)? 是一个可选的非捕获组 ((?:...)?),匹配 1 次或 0 次出现的

  • [\r\n]+ - 一个或多个 CR/LF 符号(要只匹配一个,使用 (?:\r?\n|\r|\n)
  • [^\S\r\n]+ - 除了非空白和 CR/LFs 之外的 1 个或多个符号(因此,它仅匹配水平空白
  • .* - 行的其余部分(. 在没有 DOTALL 模式的情况下默认不匹配换行符)。

此外,我建议转义 . 以匹配 IP 地址内的文字点,并将 \w 替换为 \d 以仅匹配数字。

如果第一个 O 出现在行首,为了安全起见,在它前面添加 ^

试试这个:

regex = re.findall("(?s)O\s+(?P<O>\w+.\w+.\w+.\w+.*)", output, re.M)

我添加 (?s) 以添加 s 标志以匹配空格。