Python正则表达式-re.search()与re.findall()

2024-06-08 04:12:38 发布

您现在位置:Python中文网/ 问答频道 /正文

对于学校,我应该写一个Python脚本来提取IP地址。我使用的正则表达式似乎与re.search()一起工作,但与re.findall()一起工作。

exp = "(\d{1,3}\.){3}\d{1,3}"
ip = "blah blah 192.168.0.185 blah blah"
match = re.search(exp, ip)
print match.group()

它的匹配值总是192.168.0.185,但是当我这样做时,它就不同了

exp = "(\d{1,3}\.){3}\d{1,3}"
ip = "blah blah 192.168.0.185 blah blah"
matches = re.findall(exp, ip)
print matches[0]

0.

我想知道为什么re.findall()产生0。当re.search()产生192.168.0.185时,因为我对这两个函数使用相同的表达式。

我该怎么做才能让re.findall()真正正确地遵循表达式?还是我犯了什么错误?


Tags: 函数ipre脚本search表达式match错误
2条回答

findall返回匹配项列表,并从文档中:

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

所以,前面的表达式有一个组在字符串中匹配了3次,最后一个匹配是0.

若要解决问题,请使用:exp = "(?:\d{1,3}\.){3}\d{1,3}";通过使用非分组版本,不会返回任何组,因此在这两种情况下都会返回匹配项。

你只捕获了正则表达式中的0,因为它将是最后一个捕获的。

将表达式更改为捕获整个IP,将重复部分更改为非捕获组:

In [2]: ip = "blah blah 192.168.0.185 blah blah"

In [3]: exp = "((?:\d{1,3}\.){3}\d{1,3})"

In [4]: m = re.findall(exp, ip)

In [5]: m
Out[5]: ['192.168.0.185']

In [6]: 

如果这有助于解释regex:

In [6]: re.compile(exp, re.DEBUG)
subpattern 1
  max_repeat 3 3
    subpattern None
      max_repeat 1 3
        in
          category category_digit
      literal 46
  max_repeat 1 3
    in
      category category_digit

这解释了子模式。子模式1是被findall捕获的。

相关问题 更多 >

    热门问题