Synbitz Prowduczions
Synbitz Prowduczions

Reputation: 387

Python pattern matching with regex, findall and groups

I had a script that scanned in piece of text and returned me a group which I would save to an array. The code looks like this:

pattern = re.compile(r'<span id="first_name">(.+?)</span>')
matches = pattern.findall(str(my_text_file))

This works awesome and I could scan first names in my text file and write them into an array doing this:

for firstname in matches:
    if firstname not in list_of_names:
        list_of_names.append(firstname)

But now I need to expand my pattern to retrieve two groups instead of one, and I have no idea how I am supposed to get to the second group.

When I have something like:

pattern = re.compile(r'<span id="first_name">(.+?)</span><span id="last_name">(.+?)</span>')
matches = pattern.findall(str(my_text_file))

How am I supposed to put those second group (last names) in a different array?

Upvotes: 0

Views: 1969

Answers (1)

Cito
Cito

Reputation: 5613

for match in matches:
    first_names.append(match[0])
    last_names.append(match[1])

Upvotes: 2

Related Questions