2

有人可以向我解释为什么这不匹配,而我收到的是不可接受的。

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

谢谢

4

2 回答 2

3

使用search代替match

pat = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
test = pat.search(linesout)

如果你想使用,match那么在正则表达式前面加上.*

pat = re.compile(".*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
test = pat.match(linesout)

两种情况下的输出:

Acceptable ip address

引用search() 与 match()的文档

Python 基于正则表达式提供了两种不同的原始操作: re.match() 仅在字符串的开头检查匹配,而 re.search() 在字符串中的任何位置检查匹配(这是 Perl 默认所做的) )。

于 2013-10-17T19:26:00.557 回答
-1
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")
于 2017-11-10T19:17:58.030 回答