egidra
egidra

Reputation: 9087

Getting text between brackets using regex and re

I have an array of strings that I want to extract specific content from:

['link.description', 'button.text]] </li>']

I want to get the following output:

link.description
button.text

For each string in the array, I do the following:

str = re.findall('(.*?)\]+', str)

With the above regex, I can only get button.text. How would I get both link.description and button.text? I tried using:

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

But the above just gives me a bunch of blanks in the return str.

Upvotes: 2

Views: 425

Answers (2)

user1099383
user1099383

Reputation:

Hm, try \]+. Is that what you want? (Asterisk says "match zero times or more" which -as you can see- matches really often.)

Upvotes: 0

stranac
stranac

Reputation: 28236

You don't need regex for a simple task like this. Besides, your code will probably make more sense without regex.

In this case, you can simply use str.split():

>>> thingies = ['link.description', 'button.text]] </li>']
>>> different_thingies = [thingy.split(']')[0] for thingy in thingies]
>>> different_thingies
['link.description', 'button.text']

Upvotes: 3

Related Questions