Python正则findall函数捕获分组的问题

By | May 1, 2020

Python下 findall()函数在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

但是如果正则表达式里面有()分组的话,它默认是要返回所有的满足条件的分组,返回元组格式

例如

html = ”’103.216.82.199:6667
174.70.241.7:24385”’
pattern = re.compile(r'(([0-9]{1,3}\.){3}([0-9]{1,3}):[0-9]{1,5})’)
proxies = pattern.findall(html)
//   [(‘103.216.82.199:6667′, ’82.’, ‘199’), (‘174.70.241.7:24385’, ‘241.’, ‘7’)]
返回的就是包含子组的元组,然后组成列表,
可使用
proxies = [match[0] for match in pattern.findall(html)]
//  [‘103.216.82.199:6667’, ‘174.70.241.7:24385’]
获取对应的子组内容
如果需要取消捕获分组的话,对应子组括号加上?:
pattern = re.compile(r'(?:(?:[0-9]{1,3}\.){3}(?:[0-9]{1,3}):[0-9]{1,5})’)
proxies = pattern.findall(html)
//  [‘103.216.82.199:6667’, ‘174.70.241.7:24385’]
结果则返回正则匹配的所有内容

Leave a Reply