正则表达式常用符号大全 从基础到精通 一文掌握所有元字符与语法规则

正则表达式(Regular Expression,简称 regex 或 regexp)是一种用于描述字符串模式的强大工具。它广泛应用于文本搜索、数据验证、字符串替换等场景,几乎在所有编程语言中都得到支持,如 Python、JavaScript、Java 等。从基础的简单匹配到高级的复杂解析,正则表达式都能高效处理。本篇文章将从基础概念入手,逐步深入介绍所有常用元字符和语法规则,帮助你从入门到精通。我们将通过详细的解释和完整的代码示例(以 Python 为例,因为其正则库 re 模块简单易用)来阐述每个部分,确保你能轻松理解和应用。
正则表达式基础概念
正则表达式本质上是一种模式匹配语言,用于定义字符串的规则。基础概念包括元字符(metacharacters,即特殊符号,如 .、* 等)和普通字符(如字母、数字)。正则引擎会尝试在目标字符串中找到匹配该模式的子串。
为什么使用正则表达式?
它可以处理复杂的字符串模式,而无需编写大量 if-else 语句。例如,验证邮箱格式只需一行正则,而不是多行代码。
基本工作原理
:正则表达式从左到右匹配字符串。如果找到匹配,返回成功;否则失败。匹配可以是“贪婪”(尽可能多地匹配)或“非贪婪”(尽可能少地匹配)。
在 Python 中,使用
re
模块处理正则:
import re

# 示例:简单匹配
pattern = r”hello” # r 表示原始字符串,避免转义问题
text = “hello world”
match = re.search(pattern, text) # search 查找第一个匹配
if match:
print(“匹配成功:”, match.group()) # 输出: hello
else:
print(“匹配失败”)
这个例子展示了如何在字符串中查找 “hello”。
re.search()
是最常用的方法之一,它返回一个匹配对象,如果未找到则返回 None。
常用元字符详解
元字符是正则表达式的核心,用于定义模式的结构。以下是所有常用元字符的分类和解释,每个都附带示例。
1. 基本匹配元字符
.(点)
:匹配除换行符(\n)外的任意单个字符。
示例:
a.c
匹配 “abc”、”a c”,但不匹配 “ac”(缺少一个字符)。
Python 代码:
import re
pattern = r”a.c”
texts = [“abc”, “a c”, “ac”, “a\nbc”]
for text in texts:
if re.search(pattern, text):
print(f”‘{text}’ 匹配”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘abc’ 匹配, ‘a c’ 匹配, ‘ac’ 不匹配, ‘a\nbc’ 不匹配(因为 . 不匹配换行)
^(脱字符)
:匹配字符串的开头。
示例:
^hello
匹配以 “hello” 开头的字符串,如 “hello world”,但不匹配 “say hello”。
Python 代码:
pattern = r”^hello”
texts = [“hello world”, “say hello”]
for text in texts:
if re.search(pattern, text):
print(f”‘{text}’ 匹配”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘hello world’ 匹配, ‘say hello’ 不匹配
$(美元符号)
:匹配字符串的结尾。
示例:
world$
匹配以 “world” 结尾的字符串,如 “hello world”,但不匹配 “world hello”。
Python 代码:
pattern = r”world$”
texts = [“hello world”, “world hello”]
for text in texts:
if re.search(pattern, text):
print(f”‘{text}’ 匹配”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘hello world’ 匹配, ‘world hello’ 不匹配
2. 量词(Quantifiers):控制匹配次数
量词用于指定前面的字符或组的重复次数。
***
(星号)
:匹配前面的元素 0 次或多次(贪婪模式)。
示例:
ab*c
匹配 “ac”、”abc”、”abbc” 等。
Python 代码:
pattern = r”ab*c”
texts = [“ac”, “abc”, “abbc”, “ab”]
for text in texts:
match = re.search(pattern, text)
if match:
print(f”‘{text}’ 匹配: {match.group()}”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘ac’ 匹配: ac, ‘abc’ 匹配: abc, ‘abbc’ 匹配: abbc, ‘ab’ 不匹配
+(加号)
:匹配前面的元素 1 次或多次。
示例:
ab+c
匹配 “abc”、”abbc”,但不匹配 “ac”(至少需要一个 b)。
Python 代码:
pattern = r”ab+c”
texts = [“ac”, “abc”, “abbc”]
for text in texts:
match = re.search(pattern, text)
if match:
print(f”‘{text}’ 匹配: {match.group()}”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘ac’ 不匹配, ‘abc’ 匹配: abc, ‘abbc’ 匹配: abbc
?(问号)
:匹配前面的元素 0 次或 1 次(可选)。
示例:
colou?r
匹配 “color” 和 “colour”。
Python 代码:
pattern = r”colou?r”
texts = [“color”, “colour”, “colouur”]
for text in texts:
match = re.search(pattern, text)
if match:
print(f”‘{text}’ 匹配: {match.group()}”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘color’ 匹配: color, ‘colour’ 匹配: colour, ‘colouur’ 不匹配
{n}
:精确匹配前面的元素 n 次。
示例:
a{3}
匹配 “aaa”。
{n,}
:匹配至少 n 次。
示例:
a{2,}
匹配 “aa”、”aaa” 等。
{n,m}
:匹配 n 到 m 次。
示例:
a{2,4}
匹配 “aa”、”aaa”、”aaaa”。
Python 代码(综合示例):
pattern = r”a{2,4}”
texts = [“a”, “aa”, “aaa”, “aaaa”, “aaaaa”]
for text in texts:
match = re.search(pattern, text)
if match:
print(f”‘{text}’ 匹配: {match.group()}”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘a’ 不匹配, ‘aa’ 匹配: aa, ‘aaa’ 匹配: aaa, ‘aaaa’ 匹配: aaaa, ‘aaaaa’ 匹配: aaaa(贪婪,只匹配4个)
注意
:默认是贪婪模式(尽可能多匹配)。要切换到非贪婪模式,添加 ?,如
*?
、
+?
。
3. 字符类和范围
[ ](方括号)
:定义字符类,匹配方括号内的任意一个字符。
示例:
[abc]
匹配 “a”、”b” 或 “c”。
[^ ](否定字符类)
:匹配不在方括号内的任意字符。
示例:
[^abc]
匹配除 “a”、”b”、”c” 外的任何字符。
-(连字符)
:定义范围。
示例:
[a-z]
匹配任意小写字母;
[0-9]
匹配任意数字;
[A-Za-z0-9]
匹配字母和数字。
Python 代码:
pattern = r”[a-z]+”
texts = [“abc”, “ABC”, “123”, “aBc”]
for text in texts:
match = re.search(pattern, text)
if match:
print(f”‘{text}’ 匹配: {match.group()}”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘abc’ 匹配: abc, ‘ABC’ 不匹配(因为 [a-z] 只小写), ‘123’ 不匹配, ‘aBc’ 匹配: a(只匹配小写部分)
4. 预定义字符类
这些是常用字符类的简写:
\d
:匹配任意数字,等价于
[0-9]
。
\D
:匹配任意非数字,等价于
[^0-9]
。
\w
:匹配字母、数字或下划线,等价于
[A-Za-z0-9_]
。
\W
:匹配非字母数字下划线,等价于
[^A-Za-z0-9_]
。
\s
:匹配空白字符(空格、制表符、换行等)。
\S
:匹配非空白字符。
\b
:单词边界(非字符,匹配单词前后)。
\B
:非单词边界。
示例:匹配邮箱用户名(字母数字开头和结尾)。
pattern = r”\w+@\w+\.\w+”
text = “user123@example.com”
match = re.search(pattern, text)
print(match.group()) # 输出: user123@example.com
5. 分组、捕获和引用
( )(圆括号)
:分组和捕获。匹配的子串会被捕获,可用于后续引用。
示例:
(abc)+
匹配 “abc”、”abcabc”,捕获 “abc”。
\n
:引用第 n 个捕获组(n 从 1 开始)。
示例:
(a)\1
匹配 “aa”(\1 引用第一个组的 “a”)。
(?: )
:非捕获组,只分组不捕获。
Python 代码:
pattern = r”(a)(b)\1″ # \1 引用第一个捕获组 (a)
texts = [“aba”, “abb”, “ab”]
for text in texts:
match = re.search(pattern, text)
if match:
print(f”‘{text}’ 匹配: {match.group()}, 捕获组: {match.groups()}”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘aba’ 匹配: aba, 捕获组: (‘a’, ‘b’), ‘abb’ 不匹配, ‘ab’ 不匹配
6. 选择符和转义
|(竖线)
:逻辑或,匹配左边或右边。
示例:
cat|dog
匹配 “cat” 或 “dog”。
\(反斜杠)
:转义元字符,使其作为普通字符匹配。
示例:
\.
匹配点号;
\\
匹配反斜杠。
Python 代码:
pattern = r”cat|dog”
texts = [“cat”, “dog”, “bird”]
for text in texts:
if re.search(pattern, text):
print(f”‘{text}’ 匹配”)
else:
print(f”‘{text}’ 不匹配”)
# 输出: ‘cat’ 匹配, ‘dog’ 匹配, ‘bird’ 不匹配
7. 修饰符(Flags)
修饰符改变正则的行为,常用在 Python 的
re
模块中:
re.I(忽略大小写)
:
re.compile(pattern, re.I)
。
re.M(多行模式)
:使 ^ 和 $ 匹配每行开头/结尾。
re.S(点匹配换行)
:使 . 匹配 \n。
re.X(扩展模式)
:允许注释和空格,提高可读性。
示例:忽略大小写匹配。
pattern = r”hello”
text = “HELLO world”
match = re.search(pattern, text, re.I)
print(match.group()) # 输出: HELLO
高级语法和技巧
1. 零宽断言(Lookahead 和 Lookbehind)
这些是高级匹配,不消耗字符。
(?=pattern)
:正向先行断言(后面必须是 pattern)。
示例:
\d+(?= dollars)
匹配数字后跟 “ dollars”,但不包括 “ dollars”。
(?!pattern)
:负向先行断言(后面不能是 pattern)。
(?<=pattern) :正向后行断言(前面必须是 pattern)。 (?
匹配 HTML 标签,如

,而
.*
会匹配整个字符串。
Python 代码:
pattern_greedy = r”<.*>”
pattern_non_greedy = r”<.*?>”
text = “

content

”
print(re.search(pattern_greedy, text).group()) # 输出:

content

print(re.search(pattern_non_greedy, text).group()) # 输出:

3. 常见高级应用:查找所有匹配
re.findall()
:返回所有匹配的列表。
re.finditer()
:返回迭代器,每个匹配对象。
re.sub()
:替换匹配的子串。
示例:提取所有邮箱。
pattern = r”\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b”
text = “Contact: user@example.com or admin@test.org”
emails = re.findall(pattern, text)
print(emails) # 输出: [‘user@example.com’, ‘admin@test.org’]
4. 性能优化和最佳实践
避免灾难性回溯(如嵌套量词)。
使用编译正则:
re.compile(pattern)
复用。
测试工具:在线如 regex101.com。
实际应用示例
示例 1:验证电话号码(美国格式)
模式:
^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
匹配:(123) 456-7890、123-456-7890、1234567890。
pattern = r”^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$”
phones = [“(123) 456-7890”, “123-456-7890”, “1234567890”, “123-4567″] # 最后一个不匹配
for phone in phones:
if re.match(pattern, phone): # match 从开头匹配
print(f”‘{phone}’ 有效”)
else:
print(f”‘{phone}’ 无效”)
# 输出: 有效, 有效, 有效, 无效
示例 2:解析日志文件
假设日志:
2023-10-01 12:00:00 ERROR: File not found
提取日期、级别和消息。
pattern = r”(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (\w+): (.+)”
log = “2023-10-01 12:00:00 ERROR: File not found”
match = re.match(pattern, log)
if match:
date, time, level, message = match.groups()
print(f”Date: {date}, Time: {time}, Level: {level}, Message: {message}”)
# 输出: Date: 2023-10-01, Time: 12:00:00, Level: ERROR, Message: File not found
示例 3:替换敏感信息
隐藏信用卡号的中间数字。
pattern = r”(\d{4})-(\d{4})-(\d{4})-(\d{4})”
text = “Card: 1234-5678-9012-3456″
replacement = r”\1-****-****-\4”
result = re.sub(pattern, replacement, text)
print(result) # 输出: Card: 1234-****-****-3456
常见错误和调试技巧
忘记转义
:如
.
匹配任意字符,要匹配点需
\.
。
多行 vs 单行
:默认 . 不匹配 \n,用 re.S 修复。
调试
:使用
re.DEBUG
标志查看解析过程,或在线工具可视化。
跨语言差异
:Python 的 re 与 JavaScript 的 RegExp 略有不同(如 JS 中 /pattern/flags)。
结语
掌握正则表达式需要实践,从简单模式开始,逐步构建复杂规则。本文覆盖了从基础元字符到高级断言的所有核心内容。建议多写代码测试,并参考官方文档。通过这些工具,你可以高效处理任何文本任务!如果需要特定语言的示例,随时补充。