用正则表达式在Python中拆分字符串并保留分隔符及其值

3 投票
2 回答
5561 浏览
提问于 2025-04-17 14:51

我正在尝试解析一个文本文件,这个文件里有“名字:值”这样的元素,我想把它们变成列表,格式是“名字:值”。不过有个难点:这些值有时候会是多个单词,甚至是多行的内容,而且分隔符不是固定的词。下面是我正在处理的一个例子……

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()既不太贪心也不太吝啬?

提前感谢你的阅读!

2 个回答

2

@Pavel的回答更好,但你也可以把你上次尝试的结果合并在一起:

# kill the first empty bit
if not details[0]:
    details.pop(0)

return [a + b for a, b in zip(details[::2], details[1::2])]
6

使用前瞻断言:

>>> 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!']

当然,如果你的值中有一些单词后面紧跟着冒号,这种方法还是会失败。

撰写回答