Python split string based on conditional

前端 未结 2 620
梦如初夏
梦如初夏 2021-01-13 04:51

I want to split strings using a comma delimiter if the comma is preceded by a certain regex. Consider the case where my strings are in the format: \"(bunch of stuff that mig

相关标签:
2条回答
  • 2021-01-13 05:10

    You can use a positive look-behind if the FOO_REGEX is fixed-width. Here, you will get your line split after "$$asdf,"

    See a sample working program:

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

    Output:

    ['hi, hello! $$asdf', 'I am foo, bar $$jkl, cool'] 
    
    0 讨论(0)
  • 2021-01-13 05:26

    You could use re.findall instead of 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']
    

    OR

    Use external regex module to support variable length lookbehind since re won't support variable length look-behind assertions.

    >>> 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']
    
    0 讨论(0)
提交回复
热议问题