【发布时间】:2017-11-11 23:05:59
【问题描述】:
考虑字符串s:
s = ';hello@;earth@;hello@;mars@'
我想要一个模式pat 这样我就能得到
re.split(pat, s)
[';hello@', ';earth@', ';hello@', ';mars@']
我希望 ; 和 @ 保留在结果字符串中,但我知道我想将它们分开。
我认为我可以使用前瞻和后瞻:
re.split('(?<=@)(?=;)', s)
但是,它导致了一个错误:
---------------------------------------------------------------------------
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.
【问题讨论】:
-
您也可以使用
[';' + k for k in s.split(";") if k != '']。它不是正则表达式,但可以为您提供相同的所需输出。
标签: python regex split regex-lookarounds