Pre-defining Named Recursive Subpatters In Regex
Note: I know none of this is supported in the existing re module, I am using the newer regex module intended to replace re in the future. I need to build some complex regular expre
Solution 1:
Since there is no syntax like the Perl/PCRE (?(DEFINE)....)
in the new python regex module, you can use this trick (I think that it works in Ruby too):
import regex
pattern = r'''
(?<userpart> thomas | richard | harold ){0}
(?<domainpart> gmail | yahoo | hotmail ){0}
(?<tld> com | net | co\.uk ){0}
(?<email> (?&userpart)@(?&domainpart)\.(?&tld) ){0}
^ To: \s+ .* \s+ < (?&email) > $
'''
Since you add the quantifier {0}
, you obtain zero width group definitions you can put everywhere.
Post a Comment for "Pre-defining Named Recursive Subpatters In Regex"