python re模块是进行正则表达式的一个模块,它有很多函数,例如compile,match,search,findall,split 等等。这些函数都有不同的功能来帮助开发者快速的进行字符匹配。
compile
compile 模块是笔者比较喜欢的函数,有了它正则表达式得到了复用性。
code
str = '0123456789'
com1 = re.compile('\d{10}')
com1.match(str)
re.match('\d{10}', str)
com1.match(str)
与re.match('\d{10}', str)
的功能是相同的。
match & search
可能有人会吐槽?为什么一次讲两个函数?
嗯哼,因为我想偷懒。哈哈。其实还有其他原因,因为这两个函数的功能基本相同。都是匹配一个字符串。不过前者必须是从字符的开头匹配,后者是从任何地方匹配。
code
com1 = re.compile('\d{10}')
str = 'a0123456789'
mac = com1.match(str)
sea = com1.search(str)
print sea.group() # 0123456789
print sea.start() # 1
print sea.end() # 11
sea
是一个_sre.SRE_Match
对象。
sea.group()
是匹配成功的字符串。
sea.start()
是匹配成功的字符串在原字符串的开始索引位置
sea.end()
是匹配成功的字符串在原字符串的结束索引位置
findall
findall 也是笔者比较喜欢的一个函数,它可以用于爬取网页获取固定格式的数据,当然也可以读取文本。它的作用是匹配字符串所有符合正则的字符串。以元组的方式返回回来。
code
url = urllib.urlopen('http://www.baidu.com/s?wd=hacker')
html = url.read()
bdCR = re.compile('"http://.*?"')
urls = bdCR.findall(html)
for url in urls:
print url
获取整个网页的http 连接
split
split 听名字就知道这是个分割函数,可以通过正则分割一个大文本。
ipS = re.compile('\.');
print ipS.spilt('192.168.0.1') # ['192','168','0','1']