简体   繁体   English

使用正则表达式匹配 IP 地址

[英]Using a RegEx to match IP addresses

I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...我正在尝试进行测试以检查 sys.argv 输入是否与 IP 地址的 RegEx 匹配...

As a simple test, I have the following...作为一个简单的测试,我有以下...

import re

pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")
test = pat.match(hostIP)
if test:
   print "Acceptable ip address"
else:
   print "Unacceptable ip address"

However when I pass random values into it, it returns "Acceptable IP address" in most cases, except when I have an "address" that is basically equivalent to \d+ .但是,当我将随机值传递给它时,它在大多数情况下返回“可接受的 IP 地址”,除非我有一个基本上等同于\d+的“地址”。

Using regex to validate IP address is a bad idea - this will pass 999.999.999.999 as valid.使用正则表达式来验证 IP 地址是一个坏主意 - 这将通过 999.999.999.999 作为有效。 Try this approach using socket instead - much better validation and just as easy, if not easier to do.尝试使用套接字代替这种方法 - 更好的验证和同样简单,如果不是更容易的话。

import socket

def valid_ip(address):
    try: 
        socket.inet_aton(address)
        return True
    except:
        return False

print valid_ip('10.10.20.30')
print valid_ip('999.10.20.30')
print valid_ip('gibberish')

If you really want to use parse-the-host approach instead, this code will do it exactly:如果你真的想使用解析主机方法,这段代码将完全做到:

def valid_ip(address):
    try:
        host_bytes = address.split('.')
        valid = [int(b) for b in host_bytes]
        valid = [b for b in valid if b >= 0 and b<=255]
        return len(host_bytes) == 4 and len(valid) == 4
    except:
        return False

You have to modify your regex in the following way您必须按以下方式修改正则表达式

pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")

that's because .那是因为. is a wildcard that stands for "every character"是代表“每个字符”的通配符

regex for ip v4: ip v4 的正则表达式:

^((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]?)$

otherwise you take not valid ip address like 999.999.999.999, 256.0.0.0 etc否则,您将使用无效的 IP 地址,例如 999.999.999.999、256.0.0.0 等

I came across the same situation, I found the answer with use of socket library helpful but it doesn't provide support for ipv6 addresses.我遇到了同样的情况,我发现使用套接字库的答案很有帮助,但它不提供对 ipv6 地址的支持。 Found a better way for it:找到了更好的方法:

Unfortunately, it Works for python3 only不幸的是,它仅适用于 python3

import ipaddress

def valid_ip(address):
    try: 
        print (ipaddress.ip_address(address))
        return True
    except:
        return False

print (valid_ip('10.10.20.30'))
print (valid_ip('2001:DB8::1'))
print (valid_ip('gibberish'))

You are trying to use .您正在尝试使用 . as a .作为一个 。 not as the wildcard for any character.不能作为任何字符的通配符。 Use \\.使用\\. instead to indicate a period.而是表示一个时期。

def ipcheck():
# 1.Validate the ip adderess
input_ip = input('Enter the ip:')
flag = 0

pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(pattern, input_ip)
if (match):
    field = input_ip.split(".")
    for i in range(0, len(field)):
        if (int(field[i]) < 256):
            flag += 1
        else:
            flag = 0
if (flag == 4):
    print("valid ip")
else:
    print('No match for ip or not a valid ip')
import re
ipv=raw_input("Enter an ip address")
a=ipv.split('.')
s=str(bin(int(a[0]))+bin(int(a[1]))+bin(int(a[2]))+bin(int(a[3])))
s=s.replace("0b",".")
m=re.search('\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}$',s)
if m is not None:
    print "Valid sequence of input"
else :
    print "Invalid input sequence"

Just to keep it simple I have used this approach.为了简单起见,我使用了这种方法。 Simple as in to explain how really ipv4 address is evaluated.简单地解释如何评估真正的 ipv4 地址。 Checking whether its a binary number is although not required.尽管不需要检查其是否为二进制数。 Hope you like this.希望你喜欢这个。

str = "255.255.255.255"
print(str.split('.'))

list1 = str.split('.')

condition=0

if len(list1)==4:
    for i in list1:
        if int(i)>=0 and int(i)<=255:
            condition=condition+1

if condition!=4:
    print("Given number is not IP address")
else:
    print("Given number is valid IP address")

If you really want to use RegExs, the following code may filter the non-valid ip addresses in a file, no matter the organiqation of the file, one or more per line, even if there are more text (concept itself of RegExs) :如果你真的想使用 RegExs,下面的代码可能会过滤文件中无效的 ip 地址,无论文件的组织如何,每行一个或多个,即使有更多的文本(RegExs 的概念本身):

def getIps(filename):
    ips = []
    with open(filename) as file:
        for line in file:
            ipFound = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").findall(line)
            hasIncorrectBytes = False
            try:
                    for ipAddr in ipFound:
                        for byte in ipAddr:
                            if int(byte) not in range(1, 255):
                                hasIncorrectBytes = True
                                break
                            else:
                                pass
                    if not hasIncorrectBytes:
                        ips.append(ipAddr)
            except:
                hasIncorrectBytes = True

    return ips
re.sub('((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])', '--', '127.0.0.1')

With this regular expression, only numbers from 0 to 255 could compose the address.使用这个正则表达式,只有从 0 到 255 的数字可以组成地址。 It also handles leading zeros, so 127.00.0.1 would no pass.它还处理前导零,因此127.00.0.1不会通过。

IP address uses following authentication : IP 地址使用以下身份验证:

  1. 255 ---> 250-255 255 ---> 250-255
  2. 249 ---> 200-249 249 ---> 200-249
  3. 199 ---> 100-199 199 ---> 100-199
  4. 99 ---> 10-99 99 ---> 10-99
  5. 9 ---> 1-9 9 ---> 1-9

     import re k = 0 while k < 5 : i = input("\\nEnter Ip address : ") ip = re.match("^([1][0-9][0-9].|^[2][5][0-5].|^[2][0-4][0-9].|^[1][0-9][0-9].|^[0-9][0-9].|^[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9]|[2][5][0-5]|[2][0-4][0-9]|[1][0-9][0-9]|[0-9][0-9]|[0-9])$",i) k = k + 1 if ip: print ("\\n=====================") print ("Valid IP address") print ("=====================") break else : print ("\\nInvalid IP") else : print ("\\nAllowed Max 5 times")

Reply me if you have doubt?如果您有疑问,请回复我?

import re

st1 = 'This is my IP Address10.123.56.25 789.356.441.561 127 255 123.55 192.168.1.2.3 192.168.2.2 str1'

Here my valid IP Address is only 192.168.2.2 and assuming 10.123.56.25 is not a valid one as it is combined with some string and 192.168.1.2.3 not valid.这里我的有效 IP 地址只有192.168.2.2并且假设10.123.56.25是无效的,因为它与一些字符串组合并且192.168.1.2.3无效。

pat = r'\s(((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])\s|$))'

match = re.search(pat,st1)

print match.group()

================ RESTART: C:/Python27/Srujan/re_practice.py ================
192.168.2.2 

This will grep the exact IP Address, we can ignore any pattern look like an IP Address but not a valid one.这将 grep 确切的 IP 地址,我们可以忽略任何看起来像 IP 地址但不是有效地址的模式。 Ex: 'Address10.123.56.25', '789.356.441.561' '192.168.1.2.3' .例如: 'Address10.123.56.25', '789.356.441.561' '192.168.1.2.3'

Please comment if any modifications are required.如果需要修改,请评论。

This works for python 2.7:这适用于 python 2.7:

import re
a=raw_input("Enter a valid IP_Address:")
b=("[0-9]+"+".")+"{3}"
if re.match(b,a) and b<255:
    print "Valid"
else:
    print "invalid"

""" regex for finding valid ip address """ """ 用于查找有效 IP 地址的正则表达式 """

import re


IPV4 = re.fullmatch('([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d).([0-2][0-5]{2}|\d{2}|\d)', '100.1.1.2')

if IPV4:
    print ("Valid IP address")

else:
    print("Invalid IP address")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM