匹配字符串的开头
re.match() 的第一个参数是正则表达式,第二个是要匹配的字符串:
import re
pattern = r"123"
string = "123zzb"
re.match(pattern, string)
# Out: <_sre.SRE_Match object; span=(0, 3), match='123'>
match = re.match(pattern, string)
match.group()
# Out: '123'
你可能会注意到模式变量是一个前缀为 r 的字符串,表示该字符串是原始字符串文字。
原始字符串文字与字符串文字的语法略有不同,即原始字符串文字中的反斜杠\表示只是反斜杠,并且不需要加倍反斜以转义转义序列,例如换行符(\n),tabs(\t),backspaces(\),form-feeds(\r)等。在普通的字符串文字中,每个反斜杠必须加倍,以避免被视为转义序列的开始。
因此,r"\n" 是一个由 2 个字符组成的字符串:\和 n。正则表达式模式也使用反斜杠,例如\d 指的是任何数字字符。我们可以通过使用原始字符串(r"\d")避免双重转义字符串(\\d)。
例如:
string = "\\t123zzb" # here the backslash is escaped, so there's no tab, just '\' and 't'
pattern = "\\t123" # this will match \t (escaping the backslash) followed by 123
re.match(pattern, string).group() # no match
re.match(pattern, "\t123zzb").group() # matches '\t123'
pattern = r"\\t123"
re.match(pattern, string).group() # matches '\\t123'
匹配仅从字符串的开头完成。如果你想在任何地方匹配使用 re.search 代替:
match = re.match(r"(123)", "a123zzb")
match is None
# Out: True
match = re.search(r"(123)", "a123zzb")
match.group()
# Out: '123'