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' ]
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With