潭州课堂25班:Ph201805201 第十六课 正则 (课堂笔记)

import re
元字符:  
     .  ^  $ *  +  ?   {}  \  ()

# s = 'abcdefg'
# s.find('c')
# print(s.find('cd'))          ##    查找
# b = s.replace('a', 'x')         #@#   替换
# print( b )
# c = s.split('d')                ##   分割
# print(c)

Import re
sb = re.findall('hello', 'fdasfdsafsdahellofdsafds')        ##   全部找到
print(sb)
# o = re.findall('w..l', 'hello world')        ##   .代表一个字符
o = re.findall('^hello', hellofdsfsfw)      ##   从开始查找,有则输出,
o = re.findall('hello$', hellofdsfsfw)      ##   从末尾查找,有则输出,
(‘aaaa’)=(‘a*’)  == +
(‘a…’)=(‘a.*’)  == +
o = re.findall('a?b', 'aaaaab')      ##      ?  表示0到1个a
o = re.findall('a{5}b', 'aaaaab')      ##      {}  几个自己定   {1,3}  {1,}

【】
# a = re.findall('[com cn]', 'comfdsffdscnc')           ##   二选一,三选一

a = re.findall('[a-z]', 'comfdsffdsfnc')                ##    【】a到z的范围
a = re.findall('[^c]', 'comfdsffdsfnc')                ##    【】取反 除C以外
a = re.findall( '\d{11}', 'fdsaf1234567892222' )        ##    找11个数
\d == [0-9]     \D ==[^0-9]
a = re.findall( '\sabc', 'abc  abc' )        ##   \s 空白字符
\s ==       \S  ==  
\w ==[a-Za-z0-9]  \W ==[^a-Za-z0-9]
\b  == 抓特殊字符

ret = re.search('ab', '123ab1234564897ab')
print(ret.group())                              #  #  找出满足条件的第一个结果
a = re.findall('(ab)+', 'aaabfdfwabdfd')  ##    找出ab的重复
kuo_hao = re.compile( r'\([^()]+\)' )       ##  找最里边的()

a = re.findall('(ab)|3', 'kk3')	##  或|

ret=re.search( '(?P<id>\d{3}),(?P<name>\w{3})','weeew34ttt123,ooo' )
print( ret.group())
print( ret.group('id'))
print( ret.group('name'))

m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(0))
print(m.group(1))
print(m.group(2))
'''如果正则表达式中定义了组,就可以在Match对象上用group()方法提取出子串来。
注意到group(0)永远是原始字符串,group(1)、group(2)……表示第1、2、……个子串。
'''
a = re.subn( '\d', 'abc', 'alvfdsa5y123' )          ##   替换,用 abc 替换数字

  

猜你喜欢

转载自www.cnblogs.com/gdwz922/p/9211989.html