简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM