Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string with brackets using regular expression in python

Tags:

python

regex

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?

like image 500
yvetterowe Avatar asked Feb 09 '14 17:02

yvetterowe


2 Answers

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

Regular expression visualization

Debuggex Demo

like image 128
thefourtheye Avatar answered Oct 26 '22 23:10

thefourtheye


Try this:

import re
str = "[Hi all], [this is] [an example] "
contents = re.findall('\[(.*?)\]', str)
like image 22
Jamie Bull Avatar answered Oct 27 '22 00:10

Jamie Bull