re.findall() returns a list of tuples, each of which contains the corresponding rows that correspond to the named groups in the re template. This example (using a simplified template) shows that you can access the required item with indexing:
import re prefix = 'prefix' pattern = re.compile('%s(?P<reserved>\w{4})(?P<info_hash>\w{10})(?P<peer_id>\w{10})' % prefix) handshake = 'prefix12341234567890ABCDEF1234' # sniffed data match = pattern.findall(handshake) >>> print match [('1234', '1234567890', 'ABCDEF1234')] >>> info_hash = match[0][1] >>> print info_hash 1234567890
But the point of named groups is a way to access mapped values for a named group by name. You can use re.match() :
import re prefix = 'prefix' pattern = re.compile('%s(?P<reserved>\w{4})(?P<info_hash>\w{10})(?P<peer_id>\w{10})' % prefix) handshake = 'prefix12341234567890ABCDEF1234'
Values are also available using dictionary access:
>>> d = match.groupdict() >>> d {'peer_id': 'ABCDEF1234', 'reserved': '1234', 'info_hash': '1234567890'} >>> d['info_hash'] '1234567890'
Finally, if there are several acknowledgment sequences in the input, you can use re.finditer() :
import re prefix = 'prefix' pattern = re.compile('%s(?P<reserved>\w{4})(?P<info_hash>\w{10})(?P<peer_id>\w{10})' % prefix) handshake = 'blahprefix12341234567890ABCDEF1234|randomjunkprefix12349876543210ABCDEF1234,more random junkprefix1234hellothereABCDEF1234...'
Conclusion:
1234567890
9876543210
hellothere
source share