Python正则表达式指南
import re
#
# . 代表任何单一字符
# * 代码任意一个它之前的字符
# .*代表任意多个字符(包括0个)
#match
#match只能检测以模式串为开头的源字符串
source = 'Young Frankenstein'
pattern = re.compile('You')
result = pattern.match(source)
if result:
print(result.group()) #You
print(re.match('Frank', source)) #None
print(re.match('.*Frank', source)) #<_sre.SRE_Match object; span=(0, 11), match='Young Frank'>
#search
print(re.search('Frank', source)) #<_sre.SRE_Match object; span=(6, 11), match='Frank'>
#findall
result = re.findall('n', source)
print(result) #['n', 'n', 'n', 'n']
result = re.findall('n.', source)
print(result) #['ng', 'nk', 'ns']
#split
print(re.split('n', source)) #['You', 'g Fra', 'ke', 'stei', '']
#sub 替换
print(re.sub('n', '?', source)) #You?g Fra?ke?stei?
特殊的字符
![](https://images2015.cnblogs.com/blog/382256/201608/382256-20160815132949031-1486829215.png)
![](https://images2015.cnblogs.com/blog/382256/201608/382256-20160815133025906-1693045367.png)
使用标识符
![](https://images2015.cnblogs.com/blog/382256/201608/382256-20160816024203046-1546130154.png)
![](https://images2015.cnblogs.com/blog/382256/201608/382256-20160816024213109-166377959.png)
![](https://images2015.cnblogs.com/blog/382256/201608/382256-20160816025155359-603687855.png)
![](https://images2015.cnblogs.com/blog/382256/201608/382256-20160816025203468-784229295.png)
![](https://images2015.cnblogs.com/blog/382256/201604/382256-20160426183921767-1131592766.png)
![](https://images2015.cnblogs.com/blog/382256/201605/382256-20160525150705303-40404445.png)