搜索

pattern = r"(your base)"
sentence = "All your base are belong to us."

match = re.search(pattern, sentence)
match.group(1)
# Out: 'your base'

match = re.search(r"(belong.*)", sentence)
match.group(1)
# Out: 'belong to us.'

re.match 不同,搜索在字符串中的任何位置进行。你也可以使用 re.findall

你也可以在字符串的开头搜索(使用^),

match = re.search(r"^123", "123zzb")
match.group(0)
# Out: '123'

match = re.search(r"^123", "a123zzb")
match is None
# Out: True

在字符串的末尾(使用 $),

match = re.search(r"123$", "zzb123")
match.group(0)
# Out: '123'

match = re.search(r"123$", "123zzb")
match is None
# Out: True

或两者兼得(同时使用^$):

match = re.search(r"^123$", "123")
match.group(0)
# Out: '123'