作为padraiccunningham上一个问题的解决方案的改进版本,regex ^{}将捕获所有字段。在
第一部分((["']).*?\1(?
如果第一部分不匹配(即没有用引号括起来的字符串),第二部分([^\r\n\t\f ,]+)匹配所有不是空格或逗号的内容。所以它将忽略您的分隔符,但匹配所有其他内容。在import re
rows = [""" 5,'THISMORE"THAN4','/,',4.2560,0.34000E-01 """,
# ^ added quote character here
""" 5,'TH\\'IS','/,',4.2560,0.34000E-01 """,
# ^ added escaped quote here
"""5 , 'THIS' , '/,' , 4.2560 , 0.34000E-01 """,
""" '5' 'THIS' '/,' '4.2560' '0.34000E-01' """,
""" 5,'THIS','this','/,',4.2560,0.34000E-01 """,
""" 5,'THIS','/,',4.2560,0.34000E-01 """]
pattern = re.compile(r'(["\']).*?\1(?
result = [[m.group(0).strip('"\'') for m in pattern.finditer(row)]
for row in rows]
import pprint
pprint.pprint(result)
印刷品:
^{pr2}$
仍然存在问题的是,在逗号分隔的行中包含空格的未加引号的字段。因此'hello there, "I actually", have, 5, fields'
将导致:['hello','there','I actually','have','5','fields']
你的资料里有这个吗?在