我想在另一个正则表达式中编译python regex。例如,找到如下所示的IP地址:这似乎不起作用。
>>> 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$')
在你的情况下,p_ip
只是寻找文字字符p_ip
。使用.format()
添加值。您甚至不需要将第一部分包装在re.compile
中,将其视为普通字符串。
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))
请注意,您需要将{3}
包装在双{{ }}
中,以便它被转义。