我需要使用什么模式来分割字符?
What pattern do I need to use to split in between characters?
考虑字符串 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.
错误信息真的很eloquent:re.split()
需要非空模式匹配。
Note that split
will never split a string on an empty pattern match.
你可以匹配他们:
re.findall(r';\w+@', s)
或
re.findall(r';[^@]+@', s)
re.findall
将找到匹配模式的所有非重叠实例。
;[^@]+@
模式将找到 ;
后跟 @
以外的 1+ 个符号,然后将匹配 @
,因此 ;
和 @
将在返回的项目中。
re 模块不允许在空匹配时拆分。您可以使用带有此模式的 regex module 来执行此操作:
regex.split(r'(?V1)(?<=@)(?=;)', s)
(?V1)
修饰符切换到新行为。
要获得与 re 相同的结果,您可以将 re.findall
与此模式一起使用:
re.findall(r'(?:;|^)[^@]*@*', s)
考虑字符串 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.
错误信息真的很eloquent:re.split()
需要非空模式匹配。
Note that
split
will never split a string on an empty pattern match.
你可以匹配他们:
re.findall(r';\w+@', s)
或
re.findall(r';[^@]+@', s)
re.findall
将找到匹配模式的所有非重叠实例。
;[^@]+@
模式将找到 ;
后跟 @
以外的 1+ 个符号,然后将匹配 @
,因此 ;
和 @
将在返回的项目中。
re 模块不允许在空匹配时拆分。您可以使用带有此模式的 regex module 来执行此操作:
regex.split(r'(?V1)(?<=@)(?=;)', s)
(?V1)
修饰符切换到新行为。
要获得与 re 相同的结果,您可以将 re.findall
与此模式一起使用:
re.findall(r'(?:;|^)[^@]*@*', s)