Python 如何捕获STP端口类型局部变量的表达式
文件内容:Python 如何捕获STP端口类型局部变量的表达式,python,regex,Python,Regex,文件内容: Name Type Local Value Peer Value ------------- ---- ---------------------- ---------------- STP Port Type 1 Edge Trunk Port Edge Trunk Port STP Port Guard
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 - - -
代码:
对于上述正则表达式语法的上述代码,其输出不是Python格式的,
(?:^STP\sPort\sType\s+\d\s+(\w+\s\w+\s\w+)
这里有几点:
- 修正你的缺口
- 当您使用
将文件读入变量时,行起始位置不能仅与.read()
匹配,您需要使用^
或re.M
标志使其与这些行起始位置匹配re.MULTILINE
- 要获得单个匹配,您需要
,而不是re.search
re.findall
- 如果您的
值可能包含未知数量的单词,并用1个空格分隔,则需要将模式修复为STP\u Port\u Type
。请参阅(?m)^STP\s+Port\s+Type\s+\d+\s+(\w+(?:\s\w+)
-行的开始(?m)^
-STP\s+端口\s+类型
,字之间有任意数量的空格字符STP端口类型
-1+个数字,用1+空格括起来\s+\d+\s+
-第1组:1个以上单词字符,然后是0个或多个单个空格序列,然后是1个以上单词字符(\w+(?:\s\w+*)
^STP\sPort\sType\s+\d\s+(\w+\s\w+\s\w+)
表格在这里是的,数据是这样的我相信是的数据是这样的在python中打印输出时,它没有给出任何值
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)
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)