Python3 【正则表达式】避坑指南:15个常见错误解析
本文摘要
在使用正则表达式时,初学者和中级用户经常会遇到一些常见错误。以下是 15 种常见的正则表达式错误、原因分析以及纠错方法。
1. 忘记转义特殊字符
错误:直接使用 .
、*
、+
等元字符而未转义。
import re
pattern = r'example.com'
text = "example-com"
match = re.search(pattern, text) # 无法匹配
原因:.
是元字符,匹配任意字符,而不是字面的点 .
。
纠错:使用 \.
转义。
pattern = r'example\.com'
2. 贪婪匹配导致意外结果
错误:使用 .*
或 .+
时匹配过多内容。
import re
pattern = r'<.*>'
text = "<div>Hello</div><p>World</p>"
match = re.search(pattern, text) # 匹配整个字符串
原因:*
和 +
是贪婪的,会尽可能多地匹配字符。
纠错:使用非贪婪匹配 .*?
或 .+?
。
pattern = r'<.*?>'
3. 忽略多行模式
错误:在多行文本中使用 ^
或 $
时,未启用多行模式。
import re
pattern = r'^Hello'
text = "Line1\nHello\nLine2"
match = re.search(pattern, text) # 无法匹配
原因:默认情况下,^
和 $
只匹配字符串的开头和结尾。
纠错:使用 re.MULTILINE
标志。
match = re.search(pattern, text, re.MULTILINE)
4. 字符集未正确使用
错误:在字符集中未正确使用 -
。
import re
pattern = r'[A-Z]'
text