Python正则表达式找到子串

时间:2016-04-27 06:42:12

标签: python regex

示例文本

port0 interface GigabitEthernet0/4/0

port1 interface TenGigabitEthernet0/1/0

login delay 2

bfd-template single-hop BDI

ip ftp source-interface Loopback0

ip tftp source-interface Loopback0

interface Loopback0

interface Loopback100

interface Loopback999

description *** Loopback interface for management ***

interface TenGigabitEthernet0/0/0

mtu 9216

carrier-delay msec 0

interface TenGigabitEthernet0/1/0

mtu 9216

carrier-delay msec 0

interface GigabitEthernet0/4/0

mtu 9216

interface GigabitEthernet0/4/1

我的正则表达式是

[T][e]((?:.|\n)*?[e][c]\s\d+)

并在pythex.org验证它

它匹配以下 -

TenGigabitEthernet0/1/0

mtu 9216

carrier-delay msec 0 

这就是我想要的。但它也匹配 -

TenGigabitEthernet0/1/0

login delay 2

bfd-template single-hop BDI

ip ftp source-interface Loopback0

ip tftp source-interface Loopback0

interface Loopback0

interface Loopback100

interface Loopback999

description *** Loopback interface for management ***

interface TenGigabitEthernet0/0/0

mtu 9216

carrier-delay msec 0

我不想要。我正在寻找一个multiline regex,它与我的字符串中的所有tengig-mtu-carrier-delay part(s)完全匹配。

我写的是 -

buffer_=open(file,"rb")
sb=buffer_.read().replace('\r\r\n','')
inf = re.compile(r'[T][e]((?:.|\n)*?[e][c]\s\d+)')
intf = inf.findall(sb)
print intf
buffer_.close()

它适用于顺序行中tengig-mtu-carrier-delay但不太完美的文件。如果在其他地方也找到了tengig

1 个答案:

答案 0 :(得分:0)

我认为这个正则表达式是你想要的

(tengig.*?(?:\n+)?\bmtu\b.*?(?:\n+)?\bcarrier-delay\b[^\n]+)

<强> Regex Demo

正则表达式细分

( #Capturing group
 tengig #Match tengig literally
 .*? #Lazy matching to meet next next requirement
 (?:\n+)? #Match next \n (OPTIONAL)
 \bmtu\b #Match mtu literally
 .*? #Lazy matching to meet next requirement
 (?:\n+)? #Match next \n (OPTIONAL)
 \bcarrier-delay\b #Match carrier-delay literally
 [^\n]+ #Match anything till a new line 
) #End capturing group

Python代码

p = re.compile(r'(tengig.*?(?:\n+)?\bmtu\b.*?(?:\n+)?\bcarrier-delay\b[^\n]+)', re.MULTILINE | re.IGNORECASE)
test_str = "port0 interface GigabitEthernet0/4/0\n\nport1 interface TenGigabitEthernet0/1/0\n\nlogin delay 2\n\nbfd-template single-hop BDI\n\nip ftp source-interface Loopback0\n\nip tftp source-interface Loopback0\n\ninterface Loopback0\n\ninterface Loopback100\n\ninterface Loopback999\n\ndescription * Loopback interface for management *\n\ninterface TenGigabitEthernet0/0/0\n\nmtu 9216\n\ncarrier-delay msec 0\n\ninterface TenGigabitEthernet0/1/0\n\nmtu 9216\n\ncarrier-delay msec 0\n\ninterface GigabitEthernet0/4/0\n\nmtu 9216\n\ninterface GigabitEthernet0/4/1\n"

<强> Ideone Demo