如何捕获STP端口类型局部变量的表达式

2024-05-23 19:26:53 发布

您现在位置:Python中文网/ 问答频道 /正文

文件内容:

Name                        Type  Local Value            Peer Value
-------------               ----  ---------------------- ----------------     
STP Port Type               1     Edge Trunk Port        Edge Trunk Port
STP Port Guard              1     Default                Default
STP MST Simulate PVST       1     Default                Default
Vlan xlt mapping            1     Enabled                Enabled
vPC card type               1     Orion                  Orion
Allowed VLANs               -     913                    915
Local error VLANs           -     -                      -

代码:

import re
with open('regex2+py.txt','r') as file:
o = file.read()
#print(o)
STP_Port_Type = re.findall("(?:^STP\sPort\sType\s+\d\s+(\w+\s\w+\s\w+)",o)  
print(STP_Port_Type)

对于上面的正则表达式语法(?:^STP\sPort\sType\s+\d\s+(\w+\s\w+\s\w+),上述代码的输出不是Python


Tags: 代码redefaultvalueportlocaltypeenabled
1条回答
网友
1楼 · 发布于 2024-05-23 19:26:53

这里有几点:

  • 修正你的缺口
  • 当您使用.read()将文件读入变量时,行起始位置不能仅与^匹配,您需要使用re.Mre.MULTILINE标志使其与这些行起始位置匹配
  • 要获得单个匹配,需要re.search,而不是re.findall
  • 如果您的STP_Port_Type值可能有未知数量的单词用1个空格分隔,则需要将该模式修复为(?m)^STP\s+Port\s+Type\s+\d+\s+(\w+(?:\s\w+)*)。见regex demo

使用

import re
with open('regex2+py.txt','r') as file:
    o = file.read()                  # Read the file into a variable
    STP_Port_Type = ""               # Initialize STP_Port_Type with empty string
    m = re.search("(?m)^STP\s+Port\s+Type\s+\d+\s+(\w+(?:\s\w+)*)", o) # Find a match
    if m:                            # If there is a match
        STP_Port_Type = m.group(1)   # Assign Group 1 value to STP_Port_Type
    print(STP_Port_Type)

正则表达式详细信息

  • (?m)^-行的开始
  • STP\s+Port\s+Type-STP Port Type在单词之间有任意数量的空格字符
  • \s+\d+\s+-1+个数字,用1+个空格括起来
  • (\w+(?:\s\w+)*)-组1:1+字字符,然后是单个空格的0个或多个序列,然后是1+字字符

相关问题 更多 >