【问题标题】:Python Regex: Identify the first namePython 正则表达式:识别名字
【发布时间】:2018-07-30 07:14:15
【问题描述】:

我只需要过滤“shutdown”这个词。它在单独的行中提到。但它也可以在不同的线路之间使用。我用过这个过滤器“^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

【问题讨论】:

  • 你能发布预期的输出吗?
  • 输出 = 关机。它位于 interface GigabitEthernet5/21 行下方。该行中没有其他词,只有关闭词会在那里。还有一些其他的行包含关闭我不想要这些行。我只需要关闭的线路。如果我不清楚,请告诉我。谢谢!!!
  • ^shutdown 匹配行首的字符串“shutdown”,但在您的示例输入中,行首和单词“shutdown”之间有空格。
  • 那些是网络交换机接口。之间没有空格。

标签: python regex


【解决方案1】:

要在行中仅匹配单词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。

【讨论】:

    【解决方案2】:

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

    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']
    

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多