yvetterowe
yvetterowe

Reputation: 1269

Splitting a string with brackets using regular expression in python

Suppose I have a string like str = "[Hi all], [this is] [an example] ". I want to split it into several pieces, each of which consists content inside a pair bracket. In another word, i want to grab the phrases inside each pair of bracket. The result should be like:

['Hi all', 'this is', 'an example']

How can I achieve this goal using a regular expression in Python?

Upvotes: 7

Views: 35621

Answers (3)

Peter
Peter

Reputation: 13485

I've run into this problem a few times - Regular expressions will work unless you have nested brackets. In the more general case where you might have nested brackets, the following will work:


def bracketed_split(string, delimiter, strip_brackets=False):
    """ Split a string by the delimiter unless it is inside brackets.
    e.g.
        list(bracketed_split('abc,(def,ghi),jkl', delimiter=',')) == ['abc', '(def,ghi)', 'jkl']
    """

    openers = '[{(<'
    closers = ']})>'
    opener_to_closer = dict(zip(openers, closers))
    opening_bracket = dict()
    current_string = ''
    depth = 0
    for c in string:
        if c in openers:
            depth += 1
            opening_bracket[depth] = c
            if strip_brackets and depth == 1:
                continue
        elif c in closers:
            assert depth > 0, f"You exited more brackets that we have entered in string {string}"
            assert c == opener_to_closer[opening_bracket[depth]], f"Closing bracket {c} did not match opening bracket {opening_bracket[depth]} in string {string}"
            depth -= 1
            if strip_brackets and depth == 0:
                continue
        if depth == 0 and c == delimiter:
            yield current_string
            current_string = ''
        else:
            current_string += c
    assert depth == 0, f'You did not close all brackets in string {string}'
    yield current_string
>>> list(bracketed_split("[Hi all], [this is] [an example]", delimiter=' '))
['[Hi all],', '[this is]', '[an example]']

>>> list(bracketed_split("[Hi all], [this is] [a [nested] example]", delimiter=' '))
['[Hi all],', '[this is]', '[a [nested] example]']

Upvotes: 3

Jamie Bull
Jamie Bull

Reputation: 13529

Try this:

import re
str = "[Hi all], [this is] [an example] "
contents = re.findall('\[(.*?)\]', str)

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239483

data = "[Hi all], [this is] [an example] "
import re
print re.findall("\[(.*?)\]", data)    # ['Hi all', 'this is', 'an example']

Regular expression visualization

Debuggex Demo

Upvotes: 16

Related Questions