如果URL中存在IP地址,则返回其他内容

时间:2014-02-27 16:21:28

标签: regex string matlab text-processing string-parsing

如何使用Matlab检查URL中是否存在IP地址?是否有可用于检查IP地址的功能?

data =['http://95.154.196.187/broser/6716804bc5a91f707a34479012dad47c/',
       'http://95.154.196.187/broser/',
       'http://paypal.com.cgi-bin-websc5.b4d80a13c0a2116480.ee0r-cmd-login-submit-dispatch-']

def IP_exist(data):
for b in data:
    containsdigit = any(a.isdigit() for a in b)
    if containsdigit:
        print("1")
    else:
        print("0")

1 个答案:

答案 0 :(得分:3)

使用regexp,您可以使用'tokens'或使用常规匹配的前瞻和后视。这是前瞻/后退方法:

>> str = {'http://95.154.196.187/broser/6716804bc5a91f707a34479012dad47c/',
       'http://95.154.196.187/broser/',
       'http://paypal.com.cgi-bin-websc5.b4d80a13c0a2116480.ee0r-cmd-login-submit-dispatch-'};
>> IPs = regexp(str,'(?<=//)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?=/)','match')
IPs = 
    {1x1 cell}
    {1x1 cell}
    {}
>> IPs{1}
ans = 
'95.154.196.187'
>> hasIP = ~cellfun(@isempty,IPs).'
hasIP =
     1     1     0

'tokens'方法具有更简单的模式,但输出更复杂,因为它具有嵌套单元格:

>> IPs = regexp(str,'//(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/','tokens')
IPs = 
    {1x1 cell}
    {1x1 cell}
    {}
>> IPs{1}
ans = 
    {1x1 cell}
>> IPs{1}{1}
ans = 
    '95.154.196.187'

然而,相同的hasIP计算有效。

相关问题