Reputation: 617
I would like to compile python regex inside another regex. for example find IP address like this below: This does not seem to work.
>>> import re
>>> p_ip = re.compile(r'[0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-5][0-5]')
>>> p_ip_full =re.compile( r'^(p_ip)\.{3}p_ip$')
>>> ip_str = "255.123.123.12"
>>> if (p_ip_full.match(ip_str)):
... print("match")
...
>>> p_ip_full
re.compile('^(p_ip)\\.{3}p_ip$')
Upvotes: 1
Views: 657
Reputation: 6149
In your case p_ip
is simply looking for the literal characters p_ip
. Use .format()
to add the value in. You don't even need to wrap the first part in a re.compile
, treat it as a normal string.
p_ip = r'[0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-5][0-5]'
p_ip_full = re.compile(r'^({0})\.{{3}}{0}$'.format(p_ip))
Note that you need to encase {3}
in a double {{ }}
so it gets escaped.
Upvotes: 2