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

标签 python regex string

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

例如:

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.splitpositive 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',
 '']

关于Python正则表达式根据数字后面的逗号进行分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34668217/

相关文章:

java - 将开始和结束文本替换为空

java - 尝试将 <br>、<BR>、<br +attribute> 标签替换为 <br/>

c++ - '\0' 相关问题

python - 不使用 ** 计算指数的迭代函数

python - 使用 pyJWT 和 Python 解码 Apple 的 id_token(登录)

python - 使用 pyudev 的监视器终止 USBdetector 线程

r - 如何将逗号分隔的字符串剥离为唯一的子字符串

python - 加载 keras 模型 h5 未知指标

java - 如何在 Java 中比较字符串?

c++ - 字符串逆向程序崩溃