regex to get all text outside of brackets

前端 未结 4 1766
逝去的感伤
逝去的感伤 2020-12-16 21:17

I\'m trying to grab any text outside of brackets with a regex.

Example string

Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD

相关标签:
4条回答
  • 2020-12-16 21:29

    If there are no nested brackets, you can just do this:

    re.findall(r'(.*?)\[.*?\]', example_str)
    

    However, you don't even really need a regex here. Just split on brackets:

    (s.split(']')[-1] for s in example_str.split('['))
    

    The only reason your attempt didn't work:

    re.findall(r"(.*?)\[.*\]+", example_str)
    

    … is that you were doing a non-greedy match within the brackets, which means it was capturing everything from the first open bracket to the last close bracket, instead of capturing just the first pair of brackets.


    Also, the + on the end seems wrong. If you had 'abc [def][ghi] jkl[mno]', would you want to get back ['abc ', '', ' jkl'], or ['abc ', ' jkl']? If the former, don't add the +. If it's the latter, do—but then you need to put the whole bracketed pattern in a non-capturing group: r'(.*?)(?:\[.*?\])+.


    If there might be additional text after the last bracket, the split method will work fine, or you could use re.split instead of re.findall… but if you want to adjust your original regex to work with that, you can.

    In English, what you want is any (non-greedy) substring before a bracket-enclosed substring or the end of the string, right?

    So, you need an alternation between \[.*?\] and $. Of course you need to group that in order to write the alternation, and you don't want to capture the group. So:

    re.findall(r"(.*?)(?:\[.*?\]|$)", example_str)
    
    0 讨论(0)
  • 2020-12-16 21:31

    If you want to go with regex and still handle nested brackets, you can go with:

    import re
    expr = re.compile("(?:^|])([^[\]]+)(?:\[|$)")
    
    print(expr.findall("myexpr[skip this[and this]]another[and skip that too]"))
    

    This will yield ['myexpr', 'another'].

    The idea is to match anything between the beginning of the string or a ] and the end of the string or a [.

    0 讨论(0)
  • 2020-12-16 21:35

    If there are never nested brackets:

    ([^[\]]+)(?:$|\[)
    

    Example:

    >>> import re
    >>> s = 'Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]'
    >>> re.findall(r'([^[\]]+)(?:$|\[)', s)
    ['Josie Smith ', 'Mugsy Dog Smith ']
    

    Explanation:

    ([^[\]]+)   # match one or more characters that are not '[' or ']' and place in group 1
    (?:$|\[)    # match either a '[' or at the end of the string, do not capture
    
    0 讨论(0)
  • 2020-12-16 21:38

    you can do this:

     outside = re.findall(r"[^[]+(?=\[[^]]*]|$)", example_str)
    

    In other words: All that is not an opening square bracket followed by something inside square brackets or the end of the string

    0 讨论(0)
提交回复
热议问题