python正则一篇搞掂( 二 )

print(r) 运行结果:
 ['test']r = re.findall("^test", s1, re.M)# 修饰符re.M:多行匹配print(r)运行结果:
['test', 'test']r = re.findall("^test", s1, re.I | re.M)print(r)# 输出['test', 'Test', 'test']运行结果:
['test', 'Test', 'test']2.3美元符 $匹配输入字符串的结束位置
s1 = "testingnTestingntest"r = re.findall("testing$", s1)# 默认匹配单行print(r)运行结果:
[]r = re.findall("testing$", s1, re.M)# 修饰符re.M:多行匹配print(r)# 输出['testing']运行结果:
['testing']r = re.findall("testing$", s1, re.I | re.M)# 多个修饰符通过 OR(|) 来指定print(r)# 输出['testing', 'Testing'] 运行结果:
['testing', 'Testing'] 2.4 重复元字符 *,+,?

  • * 匹配前面的子表达式任意次
  • + 匹配前面的子表达式一次或多次(至少一次)
  • ? 匹配前面的子表达式 0 次或 1 次
s1 = "znzonzoo"r = re.findall("zo*", s1)# 匹配o{0 , }print(r) 运行结果:
['z', 'zo', 'zoo'] r = re.findall("zo+", s1)   # 匹配o{1 , }
print(r)  运行结果:
['zo', 'zoo']r = re.findall("zo?", s1)# 匹配o{0 , 1}print(r)
 运行结果:
['z', 'zo', 'zo'] 2.5重复元字符 {}也是控制匹配前面的子表达式次数
【python正则一篇搞掂】s1 = "znzonzoo"r = re.findall("zo*", s1)# 匹配o{0,},逗号后不能空格r1 = re.findall(r"zo{0,}", s1)print(r)# ['z', 'zo', 'zoo']print(r1)# ['z', 'zo', 'zoo']运行结果:
['z', 'zo', 'zoo']['z', 'zo', 'zoo']r = re.findall("zo+", s1)# 匹配o{1 , }r1 = re.findall(r"zo{1,}", s1)print(r)# 输出['zo', 'zoo']print(r1)# 输出['zo', 'zoo']运行结果:
 ['zo', 'zoo']['zo', 'zoo'] r1 = re.findall("zo{2}", s1)print(r1)# 输出['zoo']运行结果:
 ['zoo']2. 6 字符组 []表示匹配给出的任意字符
s1 = "吴建国n李建国n黄建国"r = re.findall("[黄刘李]建国", s1)# 匹配包含的任意字符print(r) 运行结果:
 ['李建国', '黄建国']s1 = "testnTestingnzoo"r = re.findall("[e-o]", s1)# 匹配包含的字符范围print(r)运行结果:
 ['e', 'e', 'i', 'n', 'g', 'o', 'o'] 
s1 = "testnTestingnzoo"r = re.findall("^[tz]", s1, re.M)# 回忆脱字符 , 匹配以[tz]开头字符 。print(r)运行结果:
 ['t', 'z']s1 = "吴建国n李建国n黄建国"r = re.findall("[^黄刘李]建国", s1)# ^放到[]的里面 , 表示排除print(r)运行结果:
 ['吴建国']s1 = "testnTestingnzoo"r1 = re.findall("[^e-o]", s1)# 匹配未包含的字符范围print(r1)# 输出['t', 's', 't', 'n', 'T', 's', 't', 'n', 'z']2.7 选择元字符 |表示两个表达式选择一个匹配
s1 = "znzoodnfood"r = re.findall("z|food", s1)# 匹配"z"或"food"print(r)运行结果:
 ['z', 'z', 'food']


推荐阅读