findall 的括号问题
- import re
- s = '1213134 12121212asadqwqw192.168.1.1asadafa asqw'
- p1 = r'((2[0-4]\d|25[0-5]|1\d{2}|\d{1,2})\.){3}(2[0-4]\d|25[0-5]|1\d{2}|\d{1,2})'
- List = re.search(p1,s)
- List2 = re.findall(p1,s)
- print(List,"\n",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]|1\d{2}|\d{1,2})\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|\d{1,2})
来源: http://www.bubuko.com/infodetail-3337792.html