正则表达式

  • 正则是用于进行字符串内容的验证匹配或者搜索
  • 是一个相对独立的表达方式
  • 需要引入re模块 import re

常用的几种 re 方法

  • re.search()
1
2
3
4
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
1998 2 22, 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"))

更新: 2024-01-11 23:12:10
原文: https://www.yuque.com/zacharyblock/cx2om6/qegza164lpgh11hq