re模块的使用

re.match()

匹配字符串

在一个字符串中查找模式

import re

m = re.match('foo', 'sstafood')
if m is not None:
    print("match方法的结果:" + m.group())
n = re.search('foo', 'sstafood')
if n is not None:
    print("search方法的结果:" + n.group())

image-20220111224546416

可以看出matchsearch方法的区别

匹配多个字符串
import re

bt = 'str1|str2|str3'
m = re.match(bt, 'str2') #str2有匹配
if m is not None:
    print("第一个匹配" + m.group())
m = re.match(bt, 'str') #没有匹配
if m is not None:
    print("第二个匹配" + m.group())
m = re.search(bt, 'it is str2') #通过search搜索发现str2
if m is not None:
    print("第三个匹配" + m.group())

image-20220111225630836