python - 使用正则表达式拆分逗号、空格或分号分隔的字符串

标签 python regex

我使用正则表达式 [,;\s]+ 来拆分逗号、空格或分号分隔的字符串。如果字符串末尾没有逗号,这可以正常工作:

>>> p=re.compile('[,;\s]+')
>>> mystring='a,,b,c'
>>> p.split(mystring)
['a', 'b', 'c']

当字符串末尾有逗号时:

>>> mystring='a,,b,c,'
>>> p.split(mystring)
['a', 'b', 'c', '']

在这种情况下,我希望输出为 ['a', 'b', 'c']。

对正则表达式有什么建议吗?

最佳答案

尝试:

str = 'a,,b,c,'
re.findall(r'[^,;\s]+', str)

关于python - 使用正则表达式拆分逗号、空格或分号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815095/

相关文章:

python - 对不区分大小写的元组列表进行排序

regex - 为什么以及何时在 R 中使用可选的 perl 参数

java - @Pattern , JSR303 bean 验证 : regex check max 5 words and not blank

python - 用 Python re 替换为自定义函数

regex - Perl:试图加快解析分隔文件的速度

python - 在 Pandas 中重复行并添加序列列

__setattr__ 和 self.__dict__ 之间的 Python 交互

python - 值错误 : "too many values to unpack" when plotting with Sage

python - sqlite3 python 参数传递问题

regex - 正则表达式中反斜杠后面的数字是什么意思?