正则表达式在Python字符串处理中扮演着核心角色,尤其在搜索、替换和分割场景下效率极高。Python内置的re模块封装了所有相关功能。本文结合实例,系统讲解如何使用re模块进行字符串的匹配与替换操作,涵盖re.sub、re.search、re.match、替换函数、多模式替换、贪婪与非贪婪以及忽略大小写等技巧。
## 一、导入re模块与基础函数
使用正则表达式前必须导入re模块:
## 二、re.sub():字符串替换
re.sub()用于替换字符串中所有匹配模式的部分。语法如下:- re.sub(pattern, repl, string, count=0, flags=0)
复制代码 参数说明:
- pattern:正则表达式模式(常使用原始字符串r"..."避免转义问题)。
- repl:替换字符串或替换函数。
- string:原始字符串。
- count:最大替换次数,默认0表示全部替换。
- flags:匹配模式,如忽略大小写。
示例:将"java script"替换为"javascript":- text = "java script is awesome."
- pattern = r"\bjava script\b"
- repl = "javascript"
- new_text = re.sub(pattern, repl, text)
- print(new_text) # 输出: javascript is awesome.
复制代码
再如,将所有连续4位数字替换为"****":- text = "1234 hello 5678 world"
- pattern = r"\b\d{4}\b"
- repl = "****"
- new_text = re.sub(pattern, repl, text)
- print(f'Original: {text}')
- print(f'Replaced: {new_text}')
- # Original: 1234 hello 5678 world
- # Replaced: ****hello**** world
复制代码
## 三、re.search() 与 re.match():字符串匹配
re.search()扫描整个字符串,返回第一个匹配结果(Match对象);re.match()只从字符串开头匹配。语法:- re.search(pattern, string, flags=0)
- re.match(pattern, string, flags=0)
复制代码
示例:检查字符串是否包含"World":- text = "Hello World"
- pattern = r"World"
- match = re.search(pattern, text)
- if match:
- print("匹配成功", match.group()) # 输出: World
复制代码
re.match()示例:检查字符串是否以"Hello"开头:- text = "Hello World"
- pattern = r"Hello"
- match = re.match(pattern, text)
- if match:
- print("匹配成功", match.group()) # 输出: Hello
复制代码 注意:re.match()若开头不匹配则返回None,而re.search()会继续向后寻找。
## 四、使用替换函数实现动态替换
当替换内容依赖于匹配结果时,可传入一个函数作为repl。函数接收Match对象,返回替换字符串。
示例:将字符串中所有数字替换为两倍数值:- text = "The numbers are 123 and 456."
- pattern = r"\d+"
- def double(match):
- num = int(match.group())
- return str(num * 2)
- new_text = re.sub(pattern, double, text)
- print(new_text) # 输出: The numbers are 246 and 912.
复制代码
## 五、多模式替换(字典驱动)
若需将多个特定单词逐一替换,可使用字典定义规则并利用正则的“或”模式。为避免特殊字符干扰,先用re.escape转义键。
示例:- text = "apple banana cherry"
- rep = {"apple": "orange", "banana": "grape"}
- rep_escaped = dict((re.escape(k), v) for k, v in rep.items())
- pattern = re.compile("|".join(rep_escaped.keys()))
- new_text = pattern.sub(lambda m: rep_escaped[re.escape(m.group(0))], text)
- print(new_text) # 输出: orange grape cherry
复制代码
## 六、贪婪匹配与非贪婪匹配
默认量词(如*、+、{})是贪婪的,会尽可能匹配更多字符;在量词后加?可启用非贪婪模式。
示例:从HTML标签内提取标题内容:- text = "<title>Example</title> <body>Content</body>"
- # 贪婪匹配 (.*) 会匹配到最后一个闭合标签
- pattern_greedy = r"<title>(.*)</title>"
- match_greedy = re.search(pattern_greedy, text)
- if match_greedy:
- print("贪婪结果:", match_greedy.group(1))
- # 输出: Example</title> <body>Content
- # 非贪婪匹配 (.*?) 只匹配最近的一个
- pattern_non_greedy = r"<title>(.*?)</title>"
- match_non_greedy = re.search(pattern_non_greedy, text)
- if match_non_greedy:
- print("非贪婪结果:", match_non_greedy.group(1))
- # 输出: Example
复制代码
## 七、忽略大小写匹配
设置flags参数为re.IGNORECASE(或re.I)即可忽略大小写。
示例:- text = "Hello World"
- pattern = r"hello"
- match = re.search(pattern, text, re.IGNORECASE)
- if match:
- print("匹配成功", match.group()) # 输出: Hello
复制代码
## 八、总结
Python的re模块提供了灵活且高效的正则表达式接口。re.sub()可完成直接替换或动态替换,re.search()与re.match()负责查找,结合捕获组、量词模式和标志位,能应对绝大多数字符串处理需求。掌握这些核心用法,可极大提升文本处理的准确性与效率。实际开发中建议优先使用原生字符串定义模式,并注意贪婪与非贪婪的选择,避免匹配越界。 |