python中的正则表达式函数:匹配、替换、分割等正则表达式操作。
发布时间:2023-11-09 01:56:23
正则表达式是一种特殊的字符序列,用于匹配和操作文本字符串。Python中的re模块提供了一组函数,用于进行正则表达式的匹配、替换、分割等操作。
1. re.match(pattern, string, flags=0):尝试从字符串的起始位置匹配一个模式。如果匹配成功,返回一个匹配对象;否则,返回None。
示例:
import re
pattern = r"hello"
string = "hello world"
result = re.match(pattern, string)
if result:
print("匹配成功")
else:
print("匹配失败")
2. re.search(pattern, string, flags=0):扫描整个字符串,寻找与模式匹配的 个位置。如果匹配成功,返回一个匹配对象;否则,返回None。
示例:
import re
pattern = r"hello"
string = "world hello"
result = re.search(pattern, string)
if result:
print("匹配成功")
else:
print("匹配失败")
3. re.findall(pattern, string, flags=0):返回字符串中所有与模式匹配的子串,以列表的形式返回。
示例:
import re pattern = r"\d+" string = "abc123def456" result = re.findall(pattern, string) print(result) # 输出: ['123', '456']
4. re.finditer(pattern, string, flags=0):返回一个匹配对象的迭代器,每个匹配对象包含匹配的起始和结束位置。
示例:
import re
pattern = r"\d+"
string = "abc123def456"
result = re.finditer(pattern, string)
for match in result:
print(match.start(), match.end()) # 输出: 3 6,9 12
5. re.sub(pattern, repl, string, count=0, flags=0):使用指定的替换字符串替换原字符串中与模式匹配的所有子串。如果count参数非零,则最多替换count次。
示例:
import re pattern = r"hello" string = "hello world, hello universe" result = re.sub(pattern, "hi", string) print(result) # 输出: hi world, hi universe
6. re.split(pattern, string, maxsplit=0, flags=0):使用模式对字符串进行分割,并返回分割后的列表。maxsplit参数指定分割次数,如果非零,则最多分割maxsplit次。
示例:
import re pattern = r"\s" string = "hello world" result = re.split(pattern, string) print(result) # 输出: ['hello', 'world']
以上是Python中常用的正则表达式函数,可以用于进行字符串的匹配、替换和分割等操作。在使用正则表达式时,需要注意模式的书写和使用的标志位,以及处理函数返回值的类型和使用方式。
