2017-03-06 64 views
1

難以匹配多行的正則表達式。 我試了一些,但沒有運氣。REGEX匹配多行

的第一次嘗試: ((?:\ B#上顯示)(?:?* \ n)的{6})

結果:失敗。發現線條可以在5-8之間,有時甚至更少。所以匹配6次將不起作用。

第二次嘗試:(?< =#\ n)的(?秀*版本)

結果:失敗:對任何事情不匹配,雖然我已經使用上的成功類似的正則表達式其他比賽。

字符串我試圖匹配。

wgb-car1# show startup-config 
Using 6149 out of 32768 bytes 
! 
! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user 
! 
version 12.4 
no service pad 
service timestamps debug datetime msec 
service timestamps log datetime msec 
service password-encryption 
! 

我想匹配一切從秀的版本號。

此正則表達式的作品(RS)#秀(。*)版本,但我不知道怎麼弄的數字,因爲他們可以小數的任意組合,但始終號碼。

回答

1

您可以使用下面的正則表達式

(?s)#\sshow\s*(.*?)version\s*([\d.]+) 

DEMO

蟒蛇demo

import re 

s = """wgb-car1# show startup-config 
Using 6149 out of 32768 bytes 
! 
! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user 
! 
version 12.4 
no service pad 
service timestamps debug datetime msec 
service timestamps log datetime msec 
service password-encryption 
!""" 
r = r"(?s)#\sshow\s*(.*?)version\s*([\d.]+)" 
o = [m.group() for m in re.finditer(r, s)] 
print o 
+0

正是我一直在尋找,謝謝。 – NineTail

+0

不客氣:-) – m87

0

嘗試匹配換行到版本號和那麼不是m之後再換新線。您可以使用(?sm:show.*\nversion)獲取多行行爲(使用(?sm:...)設置),然後再使用.*$之後的非多行。

0

一個答案(其中包括)使用pos。前瞻:

\#\ show 
([\s\S]+?) 
(?=version) 

請參閱a demo on regex101.com


作爲全 Python例如:

import re 

string = """ 
wgb-car1# show startup-config 
Using 6149 out of 32768 bytes 
! 
! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user 
! 
version 12.4 
no service pad 
service timestamps debug datetime msec 
service timestamps log datetime msec 
service password-encryption 
!""" 

rx = re.compile(r''' 
    \#\ show 
    ([\s\S]+?) 
    (?=version) 
    ''', re.VERBOSE) 

matches = [match.group(0) for match in rx.finditer(string)] 
print(matches) 
# ['# show startup-config\nUsing 6149 out of 32768 bytes\n!\n! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user\n!\n']