>>> re.split("?|.", "How are you? I am talking to you. There?")
错误:
>>> re.split("? |. ", "How are you? I am talking to you. There?")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Usersgarg1AppDataLocalProgramsPythonPython310libre.py", line 230, in split
return _compile(pattern, flags).split(string, maxsplit)
File "C:Usersgarg1AppDataLocalProgramsPythonPython310libre.py", line 303, in _compile
p = sre_compile.compile(pattern, flags)
File "C:Usersgarg1AppDataLocalProgramsPythonPython310libsre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "C:Usersgarg1AppDataLocalProgramsPythonPython310libsre_parse.py", line 950, in parse
p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "C:Usersgarg1AppDataLocalProgramsPythonPython310libsre_parse.py", line 443, in _parse_sub
itemsappend(_parse(source, state, verbose, nested + 1,
File "C:Usersgarg1AppDataLocalProgramsPythonPython310libsre_parse.py", line 668, in _parse
raise source.error("nothing to repeat",
re.error: nothing to repeat at position 0
要分割的字符在正则表达式中有特殊含义。你会想要逃离他们。也许可以将它们添加到一个集合中,而不是使用|
,此时转义它们是不必要的。我们也可以用s
指定尾随空格,用+
匹配一个或多个空格。
>>> re.split(r'[?.]s+', "How are you? I am talking to you")
['How are you', 'I am talking to you']