本文目錄一覽:
如何利用Python判斷一個字符串是合法ip
首先給出一個c函數的原型:int sscanf(const char *buffer,const char *format,[argument ]…)它的返回值是參數的數據,也就是argument的個數,buffer:存儲的數據,format:格式控制字符串,argument:選擇性設定字符串。這個程序從標準流讀取數據,可以進行無限制的輸入。下面貼出代碼,然後引出另外一個問題,將字符串ip轉換成整形ip地址。[cpp]
#includestdio.h
#includestring.h
int main(void){
char str[32];
int a,b,c,d;int ret=0;
while(fgets(str,sizeof(str),stdin)!=NULL){
int len=strlen(str);
str[len]=’\0′;
ret=sscanf(str,%d.%d.%d.%d,a,b,c,d);
if(ret==4(a=0a=255)(b=0b=255)(c=0c=255)(d=0d=255)){
printf(it is ip!\n);}else
printf(it is not ip!\n);}return 0;}gcc -Wall ip.c -o ip12.3.4.5
下面來引出另外一個問題,在很多情況下,要求把字符串ip轉換成整形ip,這個問題也可以應用sscanf這個函數,首先把四個字段存儲到a,b,c,d四個變量當中去,然後進行移位運算,因為ip地址是32位的,而且是無符號整形變量,所以可以應用unsigned int 來存儲. unsinged int ip=(a24)+(b16)+(c8)+d。
python中判斷一個字符串是否是IP地址
首先給出一個c函數的原型:int sscanf(const char *buffer,const char *format,[argument ]…)它的返回值是參數的數據,也就是argument的個數,buffer:存儲的數據,format:格式控制字符串,argument:選擇性設定字符串。這個程序從標準流讀取數據,可以進行無限制的輸入。下面貼出代碼,然後引出另外一個問題,將字符串ip轉換成整形ip地址。[cpp]
#includestdio.h
#includestring.h
int main(void){
char str[32];
int a,b,c,d;int ret=0;
while(fgets(str,sizeof(str),stdin)!=NULL){
int len=strlen(str);
str[len]=’\0′;
ret=sscanf(str,%d.%d.%d.%d,a,b,c,d);
if(ret==4(a=0a=255)(b=0b=255)(c=0c=255)(d=0d=255)){
printf(it is ip!\n);}else
printf(it is not ip!\n);}return 0;}gcc -Wall ip.c -o ip12.3.4.5
下面來引出另外一個問題,在很多情況下,要求把字符串ip轉換成整形ip,這個問題也可以應用sscanf這個函數,首先把四個字段存儲到a,b,c,d四個變量當中去,然後進行移位運算,因為ip地址是32位的,而且是無符號整形變量,所以可以應用unsigned int 來存儲. unsinged int ip=(a24)+(b16)+(c8)+d。
python 怎麼用正則匹配ip?
pattern = re.compile(r'(\\\\(\d+\.){3}\d+)(\\\w+)’)
match = pattern.match(r’\\172.16.25.5\ITSOFT’)
print match.group(1) # = \\172.16.25.5
print match.group(3) # = \ITSOFT
請教Python中匹配IP的正則表達式
下面是IPv4的IP正則匹配表達式
import re
#簡單的匹配給定的字符串是否是ip地址,下面的例子它不是IPv4的地址,但是它滿足正則表達式
if re.match(r”^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$”, “272.168,1,1”):
print “IP vaild”
else:
print “IP invaild”
#精確的匹配給定的字符串是否是IP地址
if re.match(r”^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$”, “223.168.1.1”):
print “IP vaild”
else:
print “IP invaild”
#簡單的從長文本中提取中提取ip地址
string_ip = “is this 289.22.22.22 ip ?
result = re.findall(r”\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b”, string_ip)
if result:
print result
else:
print “re cannot find ip”
#精確提取IP
result = re.findall(r”\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b”, string_ip):
if result:
print result
else:
print “re cannot find ip”
下面是IPv6的正則匹配表達式
string_IPv6=”1050:0:0:0:5:600:300c:326b”
#匹配是否滿足IPv6格式要求,請注意例子里大小寫不敏感
if re.match(r”^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$”, string_IPv6, re.I):
print “IPv6 vaild”
else:
print “IPv6 invaild”
#提取IPv6,例子里大小寫不敏感
result = re.findall(r”(?![:.\w])(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}(?![:.\w])”, string_IPv6, re.I)
#打印提取結果
print result
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/243146.html