【问题标题】:What pattern do I need to use to split in between characters?我需要使用什么模式来分割字符?
【发布时间】: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


【解决方案1】:

re 模块不允许在空匹配上进行拆分。您可以使用 regex module 与此模式来做到这一点:

regex.split(r'(?V1)(?<=@)(?=;)', s)

(?V1) 修饰符切换到新行为。


要获得与 re 相同的结果,您可以将 re.findall 与此模式一起使用:

re.findall(r'(?:;|^)[^@]*@*', s)

【讨论】:

  • @piRSquared:我在第一个模式中置换了@;
  • 已确认......这如声称的那样工作......谢谢。我选择了re,因为它更容易访问,因为我必须去安装regex。但这是一个准确的答案。
  • @piRSquared:请注意,re.findall 模式的构建是为了模拟拆分模式,即使在边缘情况下也是如此:abc@;def@@@;ghi => ['abc@', ';def@@@', ';ghi']
【解决方案2】:

错误信息真的很有说服力:re.split() 需要非空模式匹配。

请注意,split 永远不会在空模式匹配上拆分字符串。

你可以匹配他们:

re.findall(r';\w+@', s)

re.findall(r';[^@]+@', s)

regex demo

re.findall 将查找匹配模式的所有非重叠出现。

;[^@]+@ 模式将找到 ; 后跟 1+ 个除 @ 之外的符号,然后将匹配 @,因此 ;@ 都将在返回的项目中。

【讨论】:

    猜你喜欢
    • 2013-06-20
    • 2017-09-05
    • 2011-12-22
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多