Skip to main content
 首页 » 编程设计

Python 正则表达式根据数字后面的逗号进行拆分

2024年10月24日29mengfanrong

我有一个大文件,我需要从中加载到一个字符串列表中。每个元素都将包含文本,直到紧跟在数字后面的“,”

例如:

this is some text, value 45789, followed by, 1245, and more text 78965, more random text 5252, 

这应该变成:

["this is some text, value 45789", "followed by, 1245", "and more text 78965", "more random text 5252"] 

我目前正在做re.sub(r'([0-9]+),','~', <input-string>)然后在“~”上拆分(因为我的文件不包含 ~)但这会抛出逗号前的数字。有什么想法吗?

请您参考如下方法:

您可以使用 re.split与 positive look-behind assertion :

>>> import re 
>>>  
>>> text = 'this is some text, value 45789, followed by, 1245, and more text 78965, more random text 5252,' 
>>> re.split(r'(?<=\d),', text) 
['this is some text, value 45789', 
 ' followed by, 1245', 
 ' and more text 78965', 
 ' more random text 5252', 
 '']