正则表达式检索与替换
re.sub用于替换字符串中的匹配项
re.sub(pattern, repl, string, count=0)
# 代码
import re
phone = "2004-959-559 # 这是一个电话号码"
# 删除注释
num = re.sub(r'#.*$', "", phone)
print("电话号码:", num)
# 移除非数字的内容
num = re.sub(r'\D', "", phone)
print("电话号码:", num)
# 将匹配的数字乘以2
def double(matched):
value = int(matched.group('value'))
return str(value * 2)
s = 'A23G4HFD567'
print(re.sub('(?P<value>\d+)', double, s))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 运行结果
电话号码: 2004-959-559
电话号码: 2004959559
A46G8HFD1134
1
2
3
2
3
1
2
3
2
3
编辑 (opens new window)
上次更新: 2022/12/31, 16:52:27
- 01
- SpringCache基本配置类05-16
- 03
- Rpamis-security-原理解析12-13