ashbyp
ashbyp

Reputation: 436

Matching some groups in a Python regex

Is it possible to construct a regex that matches as many groups as it can, giving up when the string stops matching? Eg:

import re    
s = 'a b'
m = re.search('(\w) (\w) (\w)')

I'd like m.group(1) to contain 'a' and m.group(2) to contain 'b' and m.group(3) to contain None.

But re.search() does not contain any groups in this case.

Upvotes: 0

Views: 120

Answers (1)

D_Bye
D_Bye

Reputation: 899

The pattern is looking for exactly one word character followed by one space, followed by one word character followed by one space, followed by one word character, but your string is only one letter, one space, and one letter, so will never match. You need to modify the pattern to allow for any optional parts:

import re
s = 'a b'
m = re.search('(\w) (\w)( (\w))?', s)

Note the parens around the final space and (\w) group. They create another group, which is made optional by the ? modifier. If you don't want this extra group showing up in the match object, you can make it a "non-capturing" group:

m = re.search('(\w) (\w)(?: (\w))?', s)

m will now not include a group for the (optional) final space and word character, but only for any word characters that match.

Upvotes: 3

Related Questions