I'm looking to create some python regexes by combining smaller reusable patterns and I'd like the reusable patterns to use the verbose flag. For example, suppose I had a simple pattern for digits and one for a lowercase character,
DIGIT_PATTERN = re.compile(r"""
(?P<my_digit_pattern> # start named group
\d+ # 1 or more integers
) # close named group
""", re.VERBOSE)
CHAR_PATTERN = re.compile(r"""
(?P<my_char_pattern> # start named group
[a-z] # a character
) # close named group
""", re.VERBOSE)
Is there a way I can create a new pattern that is composed of the above patterns? Something like,
NEW_PATTERN = CHAR_PATTERN followed by DIGIT PATTERN followed by CHAR_PATTERN
which I'd want to match the string a937267t
. The above examples are highly simplified, but the main point is how to combine regexes that were defined with the verbose flag.
UPDATE
This is what I have so far ... might be the only way ....
NEW_PATTERN = re.compile(
CHAR_PATTERN.pattern +
DIGIT_PATTERN.pattern +
CHAR_PATTERN.pattern,
re.VERBOSE
)
I had to ditch the named groups b/c there cant be two groups named the same thing but I think this is what I was looking for.
__add__
in re module classPattern
..., bu it's unnecessary, why don't you just finish it in your re.compile in one time . o(╯□╰)o - jia JimmyCHAR_PATTERN
is wrong or needs to be updated. - Gabriel