python 正则学习笔记

官方document

#1.0
import re
m=re.search('(?<=abc)def','cxabcdefgb')

print(m.group(0))


#1.1
m=re.search(r'(?<=-)\w+','apam-egg')

print(m.group(0))

#######################################

#2.0

s='123abc456eabc789'
print(re.findall(r'abc',s))

#2.1
s = 'I have a dog , I have a cat'
print(re.findall( r'I have a (?:dog|cat)' , s ))

print(re.findall( r'I have a dog|cat' , s ))

s='123 /n456 /n789'
print( re.findall(r'.+',s))

x = re.search('r\D+a','123chenronghua')
print(x.group())
#匹配开头,group方法返回分组字符串。
print(re.match('abc','abcefg').group()) 

r1 = re.match('abc','1abcefg') 
#开头未匹配到返回none
print(r1)   

print(re.split('[0-9]','a1b2c3'))
print(re.findall('[0-9]','a1b2c3'))

#以列表的形式返回所有匹配的子串,\d+为匹配1到多个数字
print(re.findall('\d+','a21b32c35'))
pat = re.sub('\d+','@@@','aaa1bbb22ccc333')
print(pat)   #

#只替2次匹配到的子串
print(re.sub('\d+','@@@','aaa1bbb22ccc333',count=2))

#返回repl替换的对象和替换的次数
print(re.subn('\d+','@@@','aaa1bbb22ccc333',count=2))

#提取字符串中数字
totalCount = '100abc'
too = re.sub("\D", "", totalCount)
print(too)


######################################################
######################################################
#过滤字符串中的英文与符号,保留汉字
import re
st = "hello,world!!%[545]你好234世界。。。"
ste = re.sub("[A-Za-z0-9\!\%\[\]\,\。]", "", str)
print(ste)
#从字符串中提取字母字符串
result = ''.join(re.findall(r'[A-Za-z]', st)) 
print(result)
######################################################
######################################################
posted @ 2018-07-05 17:25  luoganttcc  阅读(71)  评论(0编辑  收藏  举报