简体   繁体   中英

Python - re.search - re.compile

I'm new at this and still trying to get the parsing to work right. Any suggestions.

import urllib2
import re

## Open Connection ##
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
oururl = opener.open('http://www.ip-lookup.net')

## IP Addresss finder ##
theIP = re.compile(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}")
ip = re.search(theIP, str(oururl))

## Country finder ##
roughCountry = re.compile('([A-Z]\w+)( [A-Z]\w+){0,2}(?=\<\/a\>\s\s)')
Country = re.search(roughCountry, str(oururl))

## Print out ##
print "Your IP is:", ip
print "Your Country is:", Country

You forgot the escaping backslash in front of your digits in theIP and the dot. d{1,3}.d{1,3}.d{1,3}.d{1,3} matches things like dd.dddxdd(ddd . The regex you tried to implement I guess is \\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}

But be careful, this will also match ips like 923.234.512.235 which obviously allows numbers greater than 255. For a regex that restricts to nubers from 0-255 just give google a try. There are a million examples on an ip regex. Eg have a look here or here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM