1 import re
2
3 # ============= 笔记 =================
4 '''
5 re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
6 而re.search匹配整个字符串,直到找到一个匹配。
7
8
9 # ==================================== #
10 '''
11 # p:模式 s:要匹配的字符串
12
13
14 def match(p, s):
15 matchobj = re.search(p, s)
16 if matchobj:
17 print('匹配成功')
18 print("匹配的字符串是:", matchobj.group())
19 #print("匹配的字符串的索引是:",matchobj.start(),matchObj.end())
20 else:
21 print("匹配失败")
22
23
24 def sub(in_file, out_file):
25 with open(out_file, "w", encoding="utf-8") as f_write:
26 for line in open(in_file):
27 sub_line = re.sub('NV', 'GN', line)
28 print(sub_line)
29 f_write.write(sub_line)
30 f_write.close()
31
32
33 pattern = 'abc'
34 string = 'hello abc dog'
35 match(pattern, string)
36
37 in_file = './in.txt'
38 out_file = './out.txt'
39 sub(in_file, out_file)