使用 RegEx 匹配 IP 地址 [英] Using a RegEx to match IP addresses
本文介绍了使用 RegEx 匹配 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试进行测试以检查 sys.argv 输入是否与 IP 地址的 RegEx 匹配...
I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...
作为一个简单的测试,我有以下...
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"
但是,当我向其中传递随机值时,它在大多数情况下返回可接受的 IP 地址",除非我有一个基本上等同于 \d+
的地址".
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+
.
推荐答案
你必须按照以下方式修改你的正则表达式
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 匹配 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文