正则表达式

[TOC]

正则表达式

正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

一、[]: 一个字符集合

[] 被称为字符类,用于定义一个字符集合,匹配该集合中任意一个字符。
在方括号内列出所有可能匹配的字符,正则表达式会匹配方括号中任意一个字符。

特殊符号 含义
- 来表示一个字符范围
^ 表示排除方括号中指定的字符,例如:[ ^0-9] 非数字
\d [0-9]
\D [^0-9]
\w [a-zA-Z0-9_]
\W [^a-zA-Z0-9_]
\s 匹配任意空白字符,包括空格、制表符、换行符等
\S 匹配任意非空白字符
\b 单词边界,匹配单词的开始或结束位置,例如:\bcat\b匹配独立的单词 cat,而不会匹配 category 中的 cat
\B 非单词边界,匹配不在单词开始或结束的位置,例如:\Bing\B 对于 string 中的 ing 会匹配,而对于 sing 则不匹配

二、{}: 重复次数

{} 被称为量词,用于指定前面的元素(字符、字符类或分组)出现的次数。

特殊符号 含义
+ {1, } 1次以上
* {0,} 0次以上
? {0,1} 0次或1次、注:跟在 *+{} 等后面时,表示非贪婪匹配
. 匹配任意一个字符(换行除外)

三、特殊符号

特殊符号 含义
^ 匹配开始的字符串
$ 匹配结尾的字符串
\ 转译符,例如:\. 匹配 .\d 匹配任意数字(等价于 [0-9]
| 或者。例如:[a|b]

四、(): 分组

  1. 分组,将多个字符组合成一个整体
  2. 创建捕获组,保存匹配内容
  3. 创建非捕获组((?:)
  4. 反向引用(\数字
  1. 分组,将多个字符组合成一个整体
1
2
3
4
5
6
7
import re

# 匹配连续出现两次的 "ab"
pattern = r'(ab){2}'
text = 'abababc'
result = re.findall(pattern, text)
print(result) # ['ab']
  1. 创建捕获组,保存匹配内容
1
2
3
4
5
6
7
8
9
10
11
import re

# 匹配日期,格式为 "年-月-日",并捕获年、月、日
pattern = r'(\d{4})-(\d{2})-(\d{2})'
text = 'Today is 2024-10-15.'
result = re.search(pattern, text)
if result:
print("Full match:", result.group(0)) # Full match: 2024-10-15
print("Year:", result.group(1)) # Year: 2024
print("Month:", result.group(2)) # Month: 10
print("Day:", result.group(3)) # Day: 15
  1. 创建非捕获组((?:)
1
2
3
4
5
6
7
import re

# 使用非捕获组匹配 "abc" 或 "def" 后面跟着一个数字
pattern = r'(?:abc|def)\d'
text = 'abc1 def2 ghi3'
result = re.findall(pattern, text)
print(result) # ['abc1', 'def2']
  1. 反向引用(\数字
1
2
3
4
5
6
7
import re

# 匹配连续出现两次相同的单词
pattern = r'(\b\w+\b)\s+\1'
text = 'hello hello world'
result = re.findall(pattern, text)
print(result) # ['hello']

五、代码示例

Python中,使用re模块来实现正则表达式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import re
regex = 'a'
string = 'abc'

# 1. re.search(regex, string)
# 检查这个字符串string是否匹配正则表达式
if re.search(regex, string) is not None:
print(string) # abc

# 2. results = re.findall(regex, string)
# 匹配带正则表达式的那部分字符串
string = '2014 was a good year, but 2025 will be better!'
years = re.findall('[1-2][0-9]{3}', string)
print(years) # ['2014', '2025']

# 3. result.group(0)
# 分组提取,见上面分组

六、注意

正则表达式里使用\作为转义字符

假如你需要匹配文本中的字符\,name编程语言表示的正则表达式需要4个反斜杠\\\\,前两个和后两个分别用于在编程语言中转义成反斜杠,转换成两个反斜杠后再在正则表达式中转义成一个反斜杠。Python中的原生字符串很好的解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。同样,匹配一个数字的"\\d"可以写成r"\d",不需要再担心是否漏写了反斜杠,写出来的表达式也更直观。

1
2
3
4
5
6
import re

if re.search("\\\\", "I have one nee\dle") is not None:
print("Match")
else:
print("Not Match")
1
2
3
4
5
6
import re

if re.search(r"\\", "I have one nee\dle") is not None:
print("Match")
else:
print("Not Match")

正则表达式
https://leaf-domain.gitee.io/2025/03/22/other/正则表达式/
作者
叶域
发布于
2025年3月22日
许可协议