python正则表达式入门笔记

coding=utf-8

import re #导入re模块,用于正则表达式

st=’dabbBbcga dcgagc12g%abc010-11138495’

res=’abc’ #包含abc
res=’a[bd]c’ #包含abc或adc
res=”a[^bd]c” #除了abc和adc之外
res=’^a’ #开头是否有a
res=’bc$’ #结尾是否有bc
res=’c[0-3][0-3][a-z][a-zA-Z0-9]’

res=’\d’ #所有数字
res=’\D’ #所有非数字
res=’\s’ #所有空白
res=’\S’ #所有非空白
res=’\w’ #所有字母数字
res=’\W’ #所有非字母数字

res=’010-[\d]{8}’ #8个数字
res=’ab*’ #*代表前面字符重复0次或多次
res=’ab+’ #+代表前面字符至少出现一次
res=’010-?[\d]{8}’ #?代表前面字符出现0次或一次,即可有可无
res=’ab{1,3}’ #b出现1到3次

#print re.findall(res,st) #findall函数找匹配

—————————————————————————————————–

res='ab*'                                                                        #编译方式
p=re.compile(res)       
#print p.findall(st)

res='ab*'
p=re.compile(res,re.I)  #re.I表示不区分大小写
#print p.findall(st)
#print p.match(st)  #match开始处是否存在
y=p.search(st)      #search貌似只找一个就结束
#print y.group()

x= p.finditer(st) #返回一个迭代对象
#print x.next().group()
#-----------------------------------------------------------------------------------------------------#

st='csvt caat chut ddhad'
res='c..t'
#print re.sub(res,'python',st) #将st中满足正则条件的字符替换为python

st='123+345-47578y*344'
#print re.split('[\+\-\*]',st)


res='du.c'
#print re.findall(res,'baidu\ncom',re.S) #加上re.S后,点号可以匹配任意字符


s='''
    hello python
    adad sd
    python sa
    assd dajd
    '''
#print re.findall('^ad',s,re.M) #多行匹配


res='\w+@\w{2,3}(\.com|\.cn)'   #或,只返回()里匹配的
print re.findall(res,'[email protected]')

你可能感兴趣的:(正则表达式,python,re模块)