2016-05-02 184 views
2

我有一個字符串想匹配的字符串

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 

回答

1

您可以選擇匹配的模式後,用空格開頭的可選行:

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/LF類(因此,它的水平空白匹配其它1個或多個符號僅
  • .* - 該行的其餘部分(.默認情況下不匹配沒有DOTALL模式的換行符)。

另外,我建議逃脫.匹配字面點的IP地址內,並與\d取代\w只匹配數字。

如果第一個O出現在一行的開頭,請在出於安全起見之前添加^

+1

感謝您的建議,是的,命令爲我工作。 –

+0

很高興爲你效勞。請考慮接受答案(請參閱[如何接受SO答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)),並且如果我的答案證明對我有幫助,你(見[如何在堆棧溢出?](http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow))。 –

2

試試這個:

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

我添加(?s)添加s標誌也匹配空格。

+1

謝謝。@ aminah –

+1

[此解決方案與個別條目不匹配](https://regex101.com/r/nE4yC9/1)。 –