Markum
Markum

Reputation: 4059

How can I store multiple strings into a list from regex?

This is my string:

<span class="word">blue</span><span class="word">red</span><span class="word">yellow</span><span class="word">orange</span>

Usually I would use this just to get one result into a variable:

result = re.search('(<span class="word">)(.*)(</span>)', string)
color = result.group(2)

But now I want to get every result from my string and store each into a list. How would I go about doing this?

Upvotes: 0

Views: 366

Answers (2)

Sully
Sully

Reputation: 14943

use findall instead of search

findall() Find all substrings where the RE matches, and returns them as a list.

finditer() Find all substrings where the RE matches, and returns them as an iterator.

http://docs.python.org/howto/regex.html

Upvotes: 0

dav1d
dav1d

Reputation: 6055

There is re.findall. For larger strings I recommend re.finditer.

Upvotes: 1

Related Questions