pattern = r"\d{4}" text = "I was born in 1998" result = re.search(pattern, text) print(result)
re.match()
1 2 3 4
pattern = r"\d{4}" text = "1998 year, I was born" result = re.match(pattern, text) print(result)
re.fullmatch()
1 2 3 4
pattern = r"\d{4}" text = "1998" result = re.fullmatch(pattern, text) print(result)
re.findall()
1 2 3 4
pattern = r"\d{4}" text = "1998 2 22, I was born. My sister was born in 2006" result = re.findall(pattern, text) print(result)
re.finditer()
1 2 3 4 5
pattern = r"\d{4}" text = "1998 2 22, I was born. My sister was born in 2006" result = re.finditer(pattern, text) for res in result: print(res)
re.compile() 可以直接生成一个 re 对象,直接调用相应方法对字符串进行校验
1 2 3 4
1998222, I was born. My sister was born in 2006pattern_str = r"\d{4}" pattern_obj = re.compile(pattern_str) print(pattern_obj.search("I was born in 1998")) print(pattern_obj.findall("1998 2 22, I was born. My sister was born in 2006"))