簡體   English   中英

Python-重新搜索-重新編譯

[英]Python - re.search - re.compile

我是新手,但仍在嘗試正確地進行解析。 有什么建議么。

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

您忘記了theIP和點中數字前面的轉義反斜杠。 d{1,3}.d{1,3}.d{1,3}.d{1,3}匹配dd.dddxdd(ddd 。您嘗試實現的正則表達式我猜是\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}

但請注意,這也將匹配923.234.512.235之類的ips,顯然允許大於255的數字。對於正則表達式,其數字限制為0-255,請嘗試一下google。 ip正則表達式上有百萬個示例。 例如在這里這里看看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM