根据正则表达式分割字符串而不消耗字符

5 投票
2 回答
1032 浏览
提问于 2025-04-18 11:30
import re
textOut = re.split(r'(?=[.:,;])', text)

我想把下面这个字符串分割成一个列表

text="one,two;three.four:"

我试过用下面的方法

textOut=["one", ",two", ";three", ".four", ":"]

但是这样并没有分割出任何东西。

2 个回答

1

我不知道你的字符串里还会有什么其他情况,但这样做可以解决问题吗?

>>> s='one,two;three.four:'
>>> [x for x in re.findall(r'[.,;:]?\w*', s) if x]
['one', ',two', ';three', '.four', ':']
1

我会在这里使用 re.findall,而不是 re.split

>>> from re import findall
>>> text = "one,two;three.four:"
>>> findall("(?:^|\W)\w*", text)
['one', ',two', ';three', '.four', ':']
>>>

下面是对上面使用的正则表达式模式的详细解释:

(?:      # The start of a non-capturing group
^|\W     # The start of the string or a non-word character (symbol)
)        # The end of the non-capturing group
\w*      # Zero or more word characters (characters that are not symbols)

想了解更多信息,可以查看 这里

撰写回答