【发布时间】:2016-08-29 16:07:13
【问题描述】:
我正在尝试匹配文本文件中的字符串。我正在使用 Python 3.4.3 和正则表达式。我已经在正则表达式编辑器https://regex101.com/r/xZ7iL5/4#python 中测试了该模式。模式有效,但是当我用 python 测试时它不起作用:m 什么都不返回。
Boot_info.txt
boot.1.type=HARDDISK
boot.1.group=+Hard Drive
boot.1.name=+ST380215AS
boot.2.type=HARDDISK
boot.2.group=+Hard Drive
boot.2.name=+ST9250315AS
boot.3.type=USBKEY
boot.3.group=+Unknown Device
boot.3.name=+U1-KingstonDataTraveler G3 1.00
代码
Boot_info = "Boot_info.txt"
def Get_boot ():
global Boot_info
Indexes = []
Names = []
Types = []
Form = r"boot(.\d.)type=(.*)\n.*\nboot.\d.name=(.*)"
with open("Boot_info.txt") as Boot_info:
p = re.compile(Form)
for line in Boot_info:
m = p.match(line)
if m != None:
Index=m.group(1)
Type=m.group(2)
Name=m.group(3)
logging.info("The connected device Index is:%s",Index)
logging.info("The connected device Type is:%s",Type)
logging.info("The connected device Name is :%s",Name)
Indexes.append(Index)
Types.append(Type)
Names.append(Name)
logging.info("The connected devices Types in order are :%s", Types)
logging.info("The connected devices Names in order are :%s", Names)
else:
logging.error("Regex failed!! check the Pattern")
return (len(Indexes),Types,Names)
import re
L,typ,Nm1=Get_boot()
print('Nm1:',Nm1)
print('Length:',L)
【问题讨论】:
标签: regex python-3.x