使用正则表达式与python re.match

时间:2015-02-27 22:47:41

标签: python regex

我是python的新手,对于在字符串上使用正则表达式有疑问。目前我有:

def find_ips(ip):
    ip_str = '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
    p = re.compile(ip_str)

    m = p.match(ip)
    if m:
        print 'match found'
    else:
        print 'no match'

    global find_addr
    find_addr = p.match(ip)
    return find_addr

find_ips('this is an ip 127.0.0.1 10.0.10.5')
print find_addr

这会返回' no match'。我到目前为止还没有看到我失踪的东西。我试图从这个字符串中提取ip地址,但首先我必须找到它们。使用正则表达式编辑器,我可以使用相同的行来发现这些IP。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:2)

re.match只有在匹配字符串的开头才会找到匹配项。 re.search将在整个字符串中查找匹配项。

此外,在制作正则表达式时使用原始字符串通常是个好主意:

ip_str = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
#        ^

略有不相关的说明:

find_ips('this is an ip 127.0.0.1 10.0.10.5')
print find_addr

有点笨拙。利用调用者中的返回值要比使用全局变量的时髦东西好得多:

print find_ips('...')

答案 1 :(得分:1)

re.match()匹配字符串的开头,如果你想匹配所有内容,我会在这里使用re.findall()。在您的模式中使用原始字符串表示法也是一种很好的做法。

>>> import re
>>> def find_ips(str):
...     m = re.findall(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', str)
...     return ', '.join(m)
...
>>> print find_ips('this is an ip 127.0.0.1 10.0.10.5')
127.0.0.1, 10.0.10.5

答案 2 :(得分:0)

from re import findall                                            

# The string to be checked.
string = 'this is a string 126.32.13.1 with ips in 132.31.3.1 it'

# Print the matches of the regex in the string.
print findall('\d+\.\d+\.\d+\.\d+', string)    

# Output
# ['126.32.13.1', '132.31.3.1']