Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to get multiple elements inside square brackets

I have a string/pattern like this:

[xy][abc]

I try to get the values contained inside the square brackets:

  • xy
  • abc

There are never brackets inside brackets. Invalid: [[abc][def]]

So far I've got this:

import re
pattern = "[xy][abc]"
x = re.compile("\[(.*?)\]")
m = outer.search(pattern)
inner_value = m.group(1)
print inner_value

But this gives me only the inner value of the first square brackets.

Any ideas? I don't want to use string split functions, I'm sure it's possible somehow with RegEx alone.

like image 565
Patric Avatar asked Feb 22 '12 21:02

Patric


People also ask

What does [] used in Python?

Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.

How do you get a string between brackets in Python?

How do you get a string between brackets in Python? Use re.search() to get a part of a string between two brackets. Call re.search(pattern, string) with the pattern r"\[([A-Za-z0-9_]+)\]" to extract the part of the string between two brackets.

How do you use square brackets in Python?

The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.

How do I print a square bracket list in Python?

You can create a list by placing elements between the square brackets([]) separated by commas (,).


2 Answers

re.findall is your friend here:

>>> import re
>>> sample = "[xy][abc]"
>>> re.findall(r'\[([^]]*)\]',sample)
['xy', 'abc']
like image 139
MattH Avatar answered Oct 13 '22 15:10

MattH


>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']
like image 24
beerbajay Avatar answered Oct 13 '22 16:10

beerbajay