文件内容:
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
这里有几点:
.read()
将文件读入变量时,行起始位置不能仅与^
匹配,您需要使用re.M
或re.MULTILINE
标志使其与这些行起始位置匹配re.search
,而不是re.findall
李>STP_Port_Type
值可能有未知数量的单词用1个空格分隔,则需要将该模式修复为(?m)^STP\s+Port\s+Type\s+\d+\s+(\w+(?:\s\w+)*)
。见regex demo李>使用
正则表达式详细信息
(?m)^
-行的开始STP\s+Port\s+Type
-STP Port Type
在单词之间有任意数量的空格字符\s+\d+\s+
-1+个数字,用1+个空格括起来(\w+(?:\s\w+)*)
-组1:1+字字符,然后是单个空格的0个或多个序列,然后是1+字字符李>相关问题 更多 >
编程相关推荐