kris
kris

Reputation: 91

Extracting words between delimiters [] in python

From the below string, I want to extract the words between delimiters [ ] like 'Service Current','Service','9991','1.22':

str='mysrv events Generating Event Name [Service Current], Category [Service] Test [9991] Value [1.22]'

How can I extract the same in Python?

Upvotes: 9

Views: 36646

Answers (3)

joaquin
joaquin

Reputation: 85603

you can use regex

import re
s = re.findall('\[(.*?)\]', str)

Upvotes: 8

Vineet
Vineet

Reputation: 2231

re.findall(r'\[([^\]]*)\]', str)

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838276

First, avoid using str as a variable name. str already has a meaning in Python and by defining it to be something else you will confuse people.

Having said that you can use the following regular expression:

>>> import re
>>> print re.findall(r'\[([^]]*)\]', s)
['Service Current', 'Service', '9991', '1.22']

This works as follows:

\[   match a literal [
(    start a capturing group
[^]] match anything except a closing ]
*    zero or more of the previous
)    close the capturing group
\]   match a literal ]

An alternative regular expression is:

r'\[(.*?)\]'

This works by using a non-greedy match instead of matching anything except ].

Upvotes: 24

Related Questions