我正在尝试将其中包含 name:value 元素的文本文件解析为包含“name:value”的列表...这里有一个转折点:值有时会是多个单词甚至是多行,而分隔符不是一组固定的词。这是我正在尝试使用的示例...
listing="price:44.55 name:John Doe title:Super Widget description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!
我要返回的是...
["price:44.55", "name:John Doe", "title:Super Widget", "description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"]
这是我到目前为止尝试过的...
details = re.findall(r'[\w]+:.*', post, re.DOTALL)
["price:", "44.55 name:John Doe title:Super Widget description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"]
不是我想要的。或者……
details = re.findall(r'[\w]+:.*?', post, re.DOTALL)
["price:", "name:", "title:", "description:"]
不是我想要的。或者……
details = re.split(r'([\w]+:)', post)
["", "price:", "44.55", "name:", "John Doe", "title:", "Super Widget", "description:", "This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!"]
哪个更接近,但仍然没有骰子。另外,我可以处理一个空列表项。 所以,基本上,我的问题是如何使分隔符与 re.split() 上的值保持一致,或者如何避免 re.findall() 过于贪婪或过于吝啬?
提前感谢阅读!
最佳答案
使用前瞻断言:
>>> re.split(r'\s(?=\w+:)', post)
['price:44.55',
'name:John Doe',
'title:Super Widget',
'description:This widget slices, dices, and drives your kids to soccer practice\r\nIt even comes with Super Widget Mini!']
当然,如果您的值中有一些单词紧跟冒号,它仍然会失败。
关于python正则表达式拆分字符串,同时保持分隔符与值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715113/