python - 如何对逗号和句号使用 re.split?

标签 python regex split

我有多个字符串,其中单词用逗号或句点分隔:

string = ['apple,pear,grapes,carrot.cabbage,veggies.fruit,yard']

我想根据逗号和句点分割它:

string = ['apple','pear','grapes','carrot','cabbage','veggies','fruit','yard']

我只知道如何使用一个条件进行 re.split:

re.split(',',string)

这不会分割中间有句点的单词。如何拆分整个字符串,以便在中间有逗号或句点时拆分单词?

最佳答案

>>> import re
>>> string = 'apple,pear,grapes,carrot.cabbage,veggies.fruit,yard'
>>> re.split(',|\.',string)
['apple', 'pear', 'grapes', 'carrot', 'cabbage', 'veggies', 'fruit', 'yard']

这会拆分为 ,. (必须转义为 \. )使用更改运算符 | .

也可以用字符类来写:

>>> re.split('[,.]',string)
['apple', 'pear', 'grapes', 'carrot', 'cabbage', 'veggies', 'fruit', 'yard']

但这不太通用,因为这两个字符都不能用短语替换。

关于python - 如何对逗号和句号使用 re.split?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44099714/

相关文章:

python - 中断外部循环 Python 函数其他选项

Python 正则表达式不一致

javascript - JS 正则表达式 url 验证

performance - 在UNIX中分割文件

python - 如何设置 session 在 4 分钟内过期?

python - SQLAlchemy 多表连接

python - 使用哪个 : self or super?

javascript - 如何使用正则表达式从地址字符串中删除门牌号和入口?

python - 如何使用python中的正则表达式模块将文本字符串拆分为单词?

Java 拆分路径..?