python正则表达式拆分字符串,同时保持分隔符与值

标签 python regex

我正在尝试将其中包含 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/

相关文章:

python - 在 kivy 中,如何控制 TextInput 使用的 VKeyboard 的高度

使用正则表达式的 SQL 电子邮件验证功能

javascript - ExpressJS : What's the difference between ? 、 +、 * 在字符串模式和正则表达式中?

python - Python 中的 CSV 列表字典

Python PIL 编辑像素与 ImageDraw.point

python - 在类变量中创建对类的引用并在 __init__ 中实例化它们

python - Pycharm:有没有办法声明内置数据结构?

c++ - 从字面上理解 RegEx 中的每个字符

java - 正则表达式查找带方括号的字符串并替换

用于密码验证的 Java 正则表达式