Python 基于regexp拆分字符串而不使用字符
我想像下面这样拆分一个字符串Python 基于regexp拆分字符串而不使用字符,python,regex,string,split,Python,Regex,String,Split,我想像下面这样拆分一个字符串 text="one,two;three.four:" 列入名单 textOut=["one", ",two", ";three", ".four", ":"] 我试过了 import re textOut = re.split(r'(?=[.:,;])', text) 但是这不会分割任何内容。我不知道字符串中还会出现什么,但这会起作用吗 >>> s='one,two;three.four:' >>> [x for x in
text="one,two;three.four:"
列入名单
textOut=["one", ",two", ";three", ".four", ":"]
我试过了
import re
textOut = re.split(r'(?=[.:,;])', text)
但是这不会分割任何内容。我不知道字符串中还会出现什么,但这会起作用吗
>>> s='one,two;three.four:'
>>> [x for x in re.findall(r'[.,;:]?\w*', s) if x]
['one', ',two', ';three', '.four', ':']
我将使用此处而不是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)
有关更多信息,请参阅。谢谢,这解决了我的问题。虽然我对命令本身的理解有点迷茫,只是一个公式注释,它不像保留分隔符那样“使用字符”