Python 正则表达式 - re.search() 与 re.findall() [英] Python regular expressions - re.search() vs re.findall()
问题描述
对于学校,我应该编写一个提取 IP 地址的 Python RE 脚本.我使用的正则表达式似乎适用于 re.search()
但不适用于 re.findall()
.
For school I'm supposed to write a Python RE script that extracts IP addresses. The regular expression I'm using seems to work with re.search()
but not with 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,但是当我做 re.findall()
The match for that is always 192.168.0.185, but its different when I do re.findall()
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 时,因为我使用相同的表达式两个功能.
I'm wondering why re.findall()
yields 0. when re.search()
yields 192.168.0.185, since I'm using the same expression for both functions.
我该怎么做才能使 re.findall()
真正正确地遵循表达式?还是我犯了某种错误?
And what can I do to make it so re.findall()
will actually follow the expression correctly? Or am I making some kind of mistake?
推荐答案
findall
返回匹配列表,并从文档中:
findall
returns a list of matches, and from the documentation:
如果模式中存在一个或多个组,则返回一个团体名单;这将是一个元组列表,如果模式有不止一组.
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.
因此,您之前的表达式有一组在最后一次匹配为 0 的字符串中匹配了 3 次.
So, your previous expression had one group that matched 3 times in the string where the last match was 0.
要解决您的问题,请使用:exp = "(?:\d{1,3}\.){3}\d{1,3}"
;通过使用非分组版本,没有返回组,因此在两种情况下都返回匹配.
To fix your problem use: exp = "(?:\d{1,3}\.){3}\d{1,3}"
; by using the non-grouping version, there is no returned groups so the match is returned in both cases.
这篇关于Python 正则表达式 - re.search() 与 re.findall()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!