re模块是Python中用于处理正则表达式的标准库,它提供了一系列函数和方法来处理和匹配文本字符串。
下面是re模块的一些常用函数和方法以及它们的用法:
re.match(pattern, string, flags=0):尝试从字符串的起始位置匹配一个模式,如果匹配成功返回一个Match对象,否则返回None。
import re
pattern = r"hello"
string = "hello, world"
match_obj = re.match(pattern, string)
if match_obj:
print(match_obj.group())
![](https://img-blog.csdnimg.cn/img_convert/597d0ab0ffa302ded15342c03d6660bb.png)
re.search(pattern, string, flags=0):扫描整个字符串并返回第一个成功匹配的结果,如果匹配成功返回一个Match对象,否则返回None。
import re
pattern = r"world"
string = "hello, world"
search_obj = re.search(pattern, string)
if search_obj:
print(search_obj.group())
re.findall(pattern, string, flags=0):返回一个列表,其中包含字符串中所有与模式匹配的非重叠匹配。
import re
pattern = r"\d+"
string = "The price of the apple is 3.50 dollars."
match_list = re.findall(pattern, string)
print(match_list)
re.sub(pattern, repl, string, count=0, flags=0):返回替换后的字符串,其中所有与模式匹配的非重叠匹配都被替换成repl。
import re
pattern = r"\d+"
repl = "100"
string = "The price of the apple is 3.50 dollars."
new_string = re.sub(pattern, repl, string)
print(new_string)
re.compile(pattern, flags=0):将正则表达式模式编译成一个正则表达式对象,该对象可以用于匹配和搜索操作。
![](https://img-blog.csdnimg.cn/img_convert/a1bfad8d7d781376723e9395b3755140.png)