开发者

Regex for multi character strings embedded in rest of match?

开发者 https://www.devze.com 2023-03-05 07:51 出处:网络
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\",

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'
0

精彩评论

暂无评论...
验证码 换一张
取 消