Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 要在匹配字符串后打印下一行吗_Python_Regex_Match_Newline_String Matching - Fatal编程技术网

Python 要在匹配字符串后打印下一行吗

Python 要在匹配字符串后打印下一行吗,python,regex,match,newline,string-matching,Python,Regex,Match,Newline,String Matching,我有一根绳子 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 d

我有一根绳子

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)
但是我想把这些行和上面的输出一起打印出来

[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]+.*)?)
                              ^^^^^^^^^^^^^^^^^^^^^^^^      
O\s+(?P\d++.\d++.\d++.\d++.*([\r\n]+[^\s\r\n]+.*))
^^^^^^^^^^^^^^^^^^^^^^^^      

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

  • [\r\n]+
    -一个或多个CR/LF符号(要仅匹配一个,请使用
    (?:\r?\n | \r | \n)
  • [^\S\r\n]+
    -1个或多个非空白和CR/LFs符号(因此,它仅匹配水平空白
  • *
    -行的其余部分(
    在默认情况下不匹配没有DOTALL模式的换行符)
此外,我建议转义
以匹配IP地址内的文字点,并将
\w
替换为
\d
以仅匹配数字

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

尝试以下操作:

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

我添加<代码>(s)>代码>添加<代码> s>代码>标志,也与空白符匹配。

谢谢你的建议,是的,命令对我起作用。很高兴它对你有用。如果我的答案证明对你有用(请参阅),请考虑接受答案(见)和投票。
regex = re.findall("(?s)O\s+(?P<O>\w+.\w+.\w+.\w+.*)", output, re.M)