Tuesday, June 28, 2011

Searching for IP address using regular expression

This snippet finds an IP address in a string using regex:
import re
ip = re.compile('(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}'

match = ip.search("Your ip address is, have fun!")
if match:
 print 'IP address found:',
 print match.group(), # matching substring
 print 'at position',match.span() # indexes of the substring found
 print 'IP address not found'
The output will be
IP address found: at position (19, 30)

No comments:

Post a Comment