Python正则表达式:识别名字

时间:2018-07-30 07:14:15

标签: python regex

我只需要过滤“ 关机”这个词。它在单独的行中提到。而且它也可以在不同的行之间使用。我已经使用了此过滤器“ ^ shutdown ”和“ ^(shutdwon)”,它对我没有帮助。

我正在使用python程序进行过滤。

!
interface GigabitEthernet5/19
 switchport access vlan 102
 switchport mode access
 switchport voice vlan 100
 qos trust device cisco-phone
!
interface GigabitEthernet5/20
!
interface GigabitEthernet5/21
 description Test AP 335
 switchport access vlan 999
 switchport mode access
 shutdown
 spanning-tree portfast
!
interface GigabitEthernet5/22
!
interface GigabitEthernet5/23
 switchport access vlan 102
 switchport shutdown mode access
 switchport voice vlan 100 shutdown

2 个答案:

答案 0 :(得分:0)

要仅匹配行中的单词shutdown,可以使用以下示例(键使用标志re.MULTILINE,因为我们在正则表达式中使用了^$) :

data = """!
interface GigabitEthernet5/19
 switchport access vlan 102
 switchport mode access
 switchport voice vlan 100
 qos trust device cisco-phone
!
interface GigabitEthernet5/20
!
interface GigabitEthernet5/21
 description Test AP 335
 switchport access vlan 999
 switchport mode access
 shutdown
 spanning-tree portfast
!
interface GigabitEthernet5/22
!
interface GigabitEthernet5/23
 switchport access vlan 102
 switchport shutdown mode access
 switchport voice vlan 100 shutdown"""

import re

print(re.findall(r'^\s*(shutdown)\s*$', data, flags=re.MULTILINE))

这将打印:

['shutdown']

Detailed explanation在Regex101上。

答案 1 :(得分:0)

假定您将整个字符串视为单个变量。这是代码

import re

fp = open('testfile_data', 'r')
text = fp.read()
fp.close()
value = re.findall(r'^ shutdown$', text, re.M)
print('Input')
print(text)
print('Output')
print(value)

此处testfile_data包含与您提供的数据相同的数据。这是输出

Input
!
interface GigabitEthernet5/19
 switchport access vlan 102
 switchport mode access
 switchport voice vlan 100
 qos trust device cisco-phone
!
interface GigabitEthernet5/20
!
interface GigabitEthernet5/21
 description Test AP 335
 switchport access vlan 999
 switchport mode access
 shutdown
 spanning-tree portfast
!
interface GigabitEthernet5/22
!
interface GigabitEthernet5/23
 switchport access vlan 102
 switchport shutdown mode access
 switchport voice vlan 100 shutdown
Output
[' shutdown']