记录正则表达式+python遇到的坑

findall的括号问题

import re
s = '1213134 12121212asadqwqw192.168.1.1asadafa asqw'
p1 = r'((2[0-4]d|25[0-5]|1d{2}|d{1,2}).){3}(2[0-4]d|25[0-5]|1d{2}|d{1,2})'
List = re.search(p1,s)
List2 = re.findall(p1,s)
print(List,"
",List2)

会发现search和findall的结果不一样

<re.Match object; span=(24, 35), match='192.168.1.1'> 
 [('1.', '1', '1')]

这是因为findall遇到括号会提取括号中的数据,如果遇到多个括号则把多个括号中的内容组成元组输出,所以需要使用 ?: 来声明括号不做分组使用

所以正确的能被findall匹配IP地址的正则应该这么写
(?:(?:2[0-4]d|25[0-5]|1d{2}|d{1,2}).){3}(?:2[0-4]d|25[0-5]|1d{2}|d{1,2})
原文地址:https://www.cnblogs.com/yingyingdeyueer/p/12060583.html