Python编程实现正则表达式提取给定字符串中所有数字,Ip地址。S="汉字123数字56p192.168.3.20sfe"?
求一个python 正则表达式
#!/usr/bin/env python3
# coding=utf-8
"""
parse ip and path
"""
import re
def checkpath(s):
express = r"(\d+\.\d+\.\d+\.\d+):(.+)"
mo = re.search(express ,s)
if mo:
ip = mo.group(1)
path = mo.group(2)
print('IP is %s, path is %s' % (ip, path))
return ip, path
else:
print ('The path you input is invalid')
return None
def test_checkpath():
assert checkpath('192.168.22.77:/home/adf') == ('192.168.22.77',
'/home/adf')
assert checkpath('192.168.22:/home/adf') is None
assert checkpath('192.168.22.77/home/adf') is None
assert checkpath('192.168.22.77:') is None
需要注意re module的用法。这个只是初步判断而已,如果真要判断IP地址合法性,单用这个还不行比如每组数字必须<255这个就没作判断。path部分允许什么,是否允许空值,可以再调整。大致用法供参考。
如果不需要考虑输入合法性,直接
ip, path = input_string.split(':')
就行了。
利用正则表达式:找到一段字符串中所有的IP地址和Email地址
IP地址:(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)
邮件地址:[a-zA-Z0-9._%+-]+@(?!.*\.\..*)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}
如何提取字符串中的ip
用正则表达式 string str = "fasdfasdf192.168.0.2asdfasdf";Match m = Regex.Match(str, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}");if (m.Success) {MessageBox.Show(m.Value);}
用python怎么能解析输出ifconfig里具体IP地址?
import socket
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
print ip这就是本机的IP地址