Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by space preserving string inside curly braces

Tags:

python

regex

str = "cmd -opt1 { a b c  d e f g h } -opt2" 

I want output like this:

[ 'cmd', '-opt1', '{ a b c  d e f g h }', '-opt2' ]  
like image 844
Deepak Yadav Avatar asked Sep 08 '26 04:09

Deepak Yadav


1 Answers

In this situation, don't try to split, use re.findall:

>>> import re
>>> re.findall(r'{[^}]*}|\S+', 'cmd -opt1 { a b c  d e f g h } -opt2')
['cmd', '-opt1', '{ a b c  d e f g h }', '-opt2']

if you have to deal with nested curly brackets, the re module doesn't suffice, you need to use the "new" regex module that has the recursion feature.

>>> import regex
>>> regex.findall(r'[^{}\s]+|{(?:[^{}]+|(?R))*+}', 'cmd -opt1 { a b {c d} e f} -opt2')
['cmd', '-opt1', '{ a b {c d} e f}', '-opt2']

Where (?R) refers to the whole pattern itself.

or this one (that is better):

regex.findall(r'[^{}\s]+|{[^{}]*+(?:(?R)[^{}]*)*+}', 'cmd -opt1 { a b {c d} e f} -opt2')
like image 74
Casimir et Hippolyte Avatar answered Sep 10 '26 02:09

Casimir et Hippolyte