
Python
1. re.match():从字符串开头进行匹配。
Python
import re
s = "hello world"
matched = re.match("hello", s)
print(matched)
输出结果为:
2. re.search():在整个字符串中查找匹配项。
Python
import re
s = "hello world"
matched = re.search("world", s)
print(matched)
输出结果为:
3. re.findall():返回所有匹配的子字符串。
Python
import re
s = "hello world hello"
matched = re.findall("hello", s)
print(matched)
输出结果为:
['hello', 'hello']
4. re.sub():用新字符串替换匹配到的子字符串。
Python
import re
s = "hello world"
new_s = re.sub("world", "Python", s)
print(new_s)
输出结果为:
hello Python
以上是re模块的一些基本方法,可以根据需要使用。
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号