piR*_*red 3 python regex split regex-lookarounds
考虑字符串s:
s = ';hello@;earth@;hello@;mars@'
Run Code Online (Sandbox Code Playgroud)
我想要一个pat我得到的模式
re.split(pat, s)
[';hello@', ';earth@', ';hello@', ';mars@']
Run Code Online (Sandbox Code Playgroud)
我希望;并@保留在结果字符串中,但我知道我想在它们之间分开.
我以为我可以使用前瞻和后视:
re.split('(?<=@)(?=;)', s)
Run Code Online (Sandbox Code Playgroud)
但是,它导致了一个错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-392-27c8b02c2477> in <module>()
----> 1 re.split('(?<=@)(?=;)', s)
//anaconda/envs/3.6/lib/python3.6/re.py in split(pattern, string, maxsplit, flags)
210 and the remainder of the string is returned as the final element
211 of the list."""
--> 212 return _compile(pattern, flags).split(string, maxsplit)
213
214 def findall(pattern, string, flags=0):
ValueError: split() requires a non-empty pattern match.
Run Code Online (Sandbox Code Playgroud)
错误消息非常有说服力:re.split()需要非空模式匹配.
请注意,
split永远不会在空模式匹配上拆分字符串.
你可以匹配它们:
re.findall(r';\w+@', s)
Run Code Online (Sandbox Code Playgroud)
要么
re.findall(r';[^@]+@', s)
Run Code Online (Sandbox Code Playgroud)
请参阅正则表达式演示
该re.findall会找到匹配模式的所有非重叠的发生.
该;[^@]+@模式会发现;,随后以比其他1+符号@,然后将匹配@,因此两者;并@会返回里面的物品.