Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting words between delimiters [] in python

Tags:

python

From the below string, I want to extract the words between delimters [ ] 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?

Thanks in advance Kris

like image 304
kris Avatar asked May 17 '10 20:05

kris


People also ask

How do I extract text between brackets in Python?

The simplest way to extract the string between two parentheses is to use slicing and string. find() . First, find the indices of the first occurrences of the opening and closing parentheses. Second, use them as slice indices to get the substring between those indices like so: s[s.

How do I extract a string between two delimiters in Python?

Using index() + loop to extract string between two substrings. In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.

How do you get text between in Python?

To find a string between two strings in Python, use the re.search() method.

How do I extract a character from two symbols in Python?

How to Find a String Between Two Symbols. We can combine the index() function with slice notation to extract a substring from a string. The index() function will give us the start and end locations of the substring.


1 Answers

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 ].

like image 113
Mark Byers Avatar answered Oct 16 '22 07:10

Mark Byers