Breaking a string using brackets using regex in python

Suppose I have a type string str = "[Hi all], [this is] [an example] ". I want to break it down into several parts, each of which consists of contents within a pair. In other words, I want to capture phrases within each pair of brackets. The result should look like this:

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

How can I achieve this using regex in Python?

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

Regular expression visualization

Demo version of Debuggex

+10
source

Try the following:

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

All Articles