1

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$') 

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.