2019-02-14(情人节快乐!)--python学习笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhang_xiaomeng/article/details/87276344

参考《python核心编程》一书:

1.正则表达式:

匹配任意单个字符(.)

anyend='.end'
m=re.match(anyend,'bend')
m.group()

‘bend’

2.\w匹配字母、数字、下划线、汉字

邮箱:

patt='\w+@(\w+\.)?\w+\.com'
re.match(patt,'也可以是汉字haha11_@www1_a.xxx.com').group()
结果:
'也可以是汉字haha11_@www1_a.xxx.com'

允许任意数量的子域名存在:

patt='\w+@(\w+\.)*\w+\.com'
re.match(patt,'[email protected]').group()

结果:'[email protected]'

3.加个括号,可以构成匹配正则表达式的组

匹配子组1:

m=re.match('(\w\w\w)-(\d\d\d)','abc-123')
m.group(1)

结果:abc

匹配子组2:

m=re.match('(\w\w\w)-(\d\d\d)','abc-123')
m.group(2)

结果:

'123'

匹配所有子组:

m=re.match('(\w\w\w)-(\d\d\d)','abc-123')
m.groups()

结果:

('abc', '123')

4.开头匹配

m=re.match('^The','The end.')
m.group()

结果:“The”

5.单词边界上匹配

m=re.search(r'\bthe','bite the dog')
m.group()

结果:“The”

6.无边界

m=re.search(r'\Bthe','bitethe dog')
m.group()

结果:“the”

7.用sub()和subn()进行搜索和替换

re.sub('X','Mr. Smith','attn:X\n\nDear X,\n')

结果:'attn:Mr. Smith\n\nDear Mr. Smith,\n'

re.subn('X','Mr. Smith','attn:X\n\nDear X,\n')

结果:('attn:Mr. Smith\n\nDear Mr. Smith,\n', 2)

2表示替换次数

猜你喜欢

转载自blog.csdn.net/zhang_xiaomeng/article/details/87276344
今日推荐