regex to get all text outside of brackets

前端 未结 4 1765
逝去的感伤
逝去的感伤 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: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
    

提交回复
热议问题