1 import re
2 p1 = re.compile('.') # 代表任意的单个字符
3 print('.匹配:', p1.match('d'))
4 p2 = re.compile('jpg$') # $代表以前面字符jpg结尾的字符串(即图片文件)
5 p3 = re.compile('^p') # ^代表以p开头的字符串
6 p4 = re.compile('ca*t') # *代表a出现0次到多次
7 # RE. ab? will match either ‘a’ or ‘ab’,.?:代表任意的一个字符
8 p5 = re.compile('ca{4,6}t') # {4,6}代表a出现4次到6次
9 p6 = re.compile('ca{4}t') # {4,6}代表a恰好出现4次
10 print('{}匹配:', p6.match('caat')) # None
11 p7 = re.compile('c[abc]t') # [abc]代表a或者b或者c
12 print('[]匹配1:', p7.match('cbt'))
13 print('[]匹配2:', p7.match('cdt')) # None
14 # \s表示匹配一个空格,若是多个则\s+
15 # \S表示匹配一个非空格
16 # \d表示匹配一个数字,可以是多个,==[0-9]+
17 # \D表示匹配不包含数字的
18 # ()表示分组,如把2018-09-23分成(2018)-(09)-(23)
19 # ^$,这个组合表示空白行
20 # .*?,这个组合表示非贪婪模式,即使得匹配的字符尽可能少
21 p8 = re.compile(r'(\d+).(\d+).(\d+)') # 匹配日期,r表示不转义
22 # 比较区别print('\nhello')与print(r'\nhello')
23 print('日期匹配1:', p8.match('2020-09-23').group())
24 print('日期匹配2:', p8.match('2020-09-23').groups())
25 print('日期匹配3:', p8.match('2020-09-23').group(1, 2))
26 year, month, day = p8.match('2020-09-23').groups()
27 print(year, month, day)
28 # match需要从开始就完全匹配,而search则是所搜能够匹配的地方
29 print('search匹配:', p8.search('abc2020-09-23').group()) # 换成p8.match则会出错
30 # sub()用来做字符的替换
31 phone = '138-1234-5678 # 这是手机号码'
32 s1 = re.sub(r'#.*$', "", phone) # 将#之后到结尾的内容替换成空,即去掉
33 print('字符替换sub:', s1)
34 s2 = re.sub(r'\D', '', s1)
35 print(s2)
36 # 还有re.findall,详见extract_name.py