搜尋
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'