python正则--re

直接上例子:

[root@esearch-prod-component-010177210122 /home/liujiangbo] 01:54:27 0
# cat 2.py 
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re

ttt="133.556.777.8888,woshsinibaba"      #这里可以用nginx的访问日志
patener=re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')  #定义正则匹配规则,\d{1,3}表示1到3个数字
match = patener.match(ttt) #正则规则去ttt中匹配,这是一个对象
print("____________________________")
print(match)   
#print("____________________________")
t=match.group()     #返回正则表达式匹配到的字符串
print("____________________________")
print(t)
match1=patener.search(ttt)
print("____________________________")
t1=match1.group()
print(t1)

进行匹配:
方法 描述
match() 从字符串开头位置开始匹配
search() 对字符串的任意位置进行匹配
findall() 返回字符串中所有匹配的子串组成的列表
finditer() 返回一个包含了所有的匹配对象的迭代器

上面方法得到的是一个对象,我们得到匹配对象以后,就可以通过匹配对象中的方法对匹配的信息进行进一步的处理了。
匹配对象中重要的方法如下:
方法 描述
group() 返回正则表达式匹配到的字符串
start() 返回匹配的起始位置
end() 返回匹配的结束位置
span() 返回一个包含匹配的起始位置和结束位置的元组(start, end)
上面例子执行结果为:

[root@esearch-prod-component-010177210122 /home/liujiangbo] 01:54:26 0
# python 2.py
____________________________
<_sre.SRE_Match object at 0x7f572c47b920>
____________________________
133.556.777.888
____________________________
133.556.777.888

参考

你可能感兴趣的:(python正则--re)