首页 > 代码库 > python re模块记录

python re模块记录

import re
‘‘‘
re模块

    compile
    match search findall
    group groups

正则表达式常用格式:

  字符:\d \w \t  .
(\d:数字;\w:字母数字下划线_;\t:制表符;点.:处了回车外的所有字符)

  次数:* + ? {m} {m,n}
(+:>=1数字;*:>=0个字符;?:0或1,{m}次,{m,n}范围,包括n)
match字符串开头开始匹配,第一个不匹配就返回none
search一次寻找整个整个字符串,直到匹配为止,只返回一个匹配值
findall寻找字符串的所有,遍历整个字符串,返回所有相匹配的值

‘‘‘
#match
res1 = re.match(‘\d+‘, ‘wqe221111wd3345‘)
if res1:
    print res1.group()
else:
    print ‘nothing‘
#search
res2 = re.search(‘\d+‘,‘wqe221111wd3345‘)
if  res2:
    print res2.group()
else:
    print ‘nothing‘
#findall
res3 = re.findall(‘\d+‘,‘wqe221111wd3345‘)
print res3
#compile
com = re.compile(‘\d+‘,)
print com.findall(‘wqe221111wd3345‘)
#group groups
res4 = re.search(‘(\d+)\w*(\d+)‘,‘wqe221111wd3345‘)
print res4.group()
print res4.groups()

python re模块记录