I have a string/pattern like this:
[xy][abc]
I try to get the values contained inside the square brackets:
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.
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? 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.
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.
You can create a list by placing elements between the square brackets([]) separated by commas (,).
re.findall
is your friend here:
>>> import re
>>> sample = "[xy][abc]"
>>> re.findall(r'\[([^]]*)\]',sample)
['xy', 'abc']
>>> import re
>>> re.findall("\[(.*?)\]", "[xy][abc]")
['xy', 'abc']
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