How can I match somethi开发者_如何学Gong like "AB|CD|EF"
followed by "12|34"
and get, for instance, "AB12"
back? If the string was "zzAB34zz"
I'd get "AB34"
, "zzABCD12"
and get "CD12"
, etc?
No need for named groups here, really:
import re
re.search('(AB|CD|EF)(12|34)', 'zzAB34zz').group()
Use parentheses to capture:
import re
r = re.compile(r'(?P<stuff>(AB|CD|EF)(12|34))')
r.findall('__ABCD12__EF34__')
#[('CD12', 'CD', '12'), ('EF34', 'EF', '34')]
r.search('__ABCD12__EF34__').group('stuff')
#'CD12'
Named parentheses (?P<name>...)
can help avoid annoying indexing.
import re ; "".join(re.compile("(AB|CD|EF)(12|34)").search("zAB12z").groups())
prints out:
'AB12'
精彩评论