【问题标题】:Python split string based on conditional基于条件的Python拆分字符串
【发布时间】:2015-06-08 07:47:21
【问题描述】:

如果逗号前面有某个正则表达式,我想使用逗号分隔符拆分字符串。考虑我的字符串采用以下格式的情况: “(一堆可能有逗号的东西)FOO_REGEX,(其他可能有逗号的东西)FOO_REGEX,......”我想用逗号分割字符串,但前提是它们前面有FOO_REGEX:[“(一堆可能有逗号的东西)FOO_REGEX”,“(可能有逗号的其他东西)FOO_REGEX”,tc。]。

作为一个具体的例子,考虑拆分以下字符串:

"hi, hello! $$asdf, I am foo, bar $$jkl, cool" 

进入这个三个字符串的列表:

["hi, hello! $$asdf", 
"I am foo, bar $$jkl", 
"cool"]

在 python 中有没有简单的方法可以做到这一点?

【问题讨论】:

    标签: python regex string split


    【解决方案1】:

    您可以使用re.findall 代替re.split

    >>> import re
    >>> s = "hi, hello! $$asdf, I am foo, bar $$jkl, cool"
    >>> [j for i in re.findall(r'(.*?\$\$[^,]*),\s*|(.+)', s) for j in i if j]
    ['hi, hello! $$asdf', 'I am foo, bar $$jkl', 'cool']
    

    使用外部regex 模块来支持可变长度的后视,因为re 不支持可变长度的后视断言。

    >>> import regex
    >>> s = "hi, hello! $$asdf, I am foo, bar $$jkl, cool"
    >>> regex.split(r'(?<=\$\$[^,]*),\s*', s)
    ['hi, hello! $$asdf', 'I am foo, bar $$jkl', 'cool']
    

    【讨论】:

    • 希望尽快添加。因为你给的链接太棒了
    【解决方案2】:

    如果 FOO_REGEX 是固定宽度的,您可以使用正向后视。在这里,您将在 "$$asdf," 之后拆分行

    查看sample working program

    import re    
    str = 'hi, hello! $$asdf, I am foo, bar $$jkl, cool'
    splts = re.split('(?<=\$\$asdf), *', str)
    print splts
    

    输出:

    ['hi, hello! $$asdf', 'I am foo, bar $$jkl, cool'] 
    

    【讨论】:

      猜你喜欢
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多