Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 来自正则表达式的列表索引错误_Python_Regex - Fatal编程技术网

Python 来自正则表达式的列表索引错误

Python 来自正则表达式的列表索引错误,python,regex,Python,Regex,我有下面的函数,它给了我错误。 它应该从网站url中提取IP 有时有效有时我会出现以下错误: File "test.py", line 30, in getIPextA address = grab[0] # get address as a string IndexError: list index out of range 功能: def getIPextA(): """ Version A Get external ip from "http://c

我有下面的函数,它给了我错误。 它应该从网站url中提取IP 有时有效有时我会出现以下错误:

File "test.py", line 30, in getIPextA
address = grab[0]                    # get address as a string
IndexError: list index out of range
功能:

def getIPextA():
"""
Version A Get external ip from "http://checkip.dyndns.org/"
"""
site=geturldata("http://checkip.dyndns.org/")
if site =="" : return [0,0,0,0]
grab = re.findall('\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3}',site)
address = grab[0]                    # get address as a string
return map(int,address.split('.'))   # as an integer list

当IP地址与正则表达式不匹配时,会出现错误。原因可能是您有时有一个包含一个数字部分的IP。这些也是有效的IP。您还应该转义点,因为正则表达式中的点意味着它可以匹配任何字符

grab = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',site)

我建议这样做

    match = re.search(r' (\d{1,3}) \. (\d{1,3}) \. (\d{1,3}) \. (\d{1,3}) ', site, flags=re.X)
    return match.groups() if match else [0, 0, 0, 0]
它允许每个八位字节中有一到三个数字,并且点
也可以正确转义。
flags
参数允许我添加不重要的空格,以便正则表达式更具可读性。每个八位字节都包含在括号中,因此如果调用其
groups
方法,则
MatchObject
将返回四个十进制字符串的列表


但是我不知道你的
geturldata
函数是什么,所以我再也帮不了你了。

我可以引用那个url还是需要屏蔽它?我不知道你的意思。什么是
geturldata
?geturldata()以长字符串的形式从url页面获取所有数据,并在url失败时进行一些错误检查等。。。