什么是正则表达式
正则表达式就是记录
文本规则
的代码
基本用法
\
: 将下一个字符标记为一个特殊字符.
d # 普通字符
\d # 0-9 正整数
s # 普通字符
\s # 空白符,比如\t,\n
定界符
^
: 匹配输入字符串的开始位置$
: 匹配输入字符串的结束位置
正则: ^123.*123$ # 匹配123hello123
\b
: 匹配一个单词边界,也就是指单词和空格间的位置
teacher Li
正则: er\b # 可以匹配出er
\B
: 匹配非单词边界
verb
正则: er\B # 可以匹配出er
个数/次数
*
: 匹配前面的子表达式零次或多次+
: 匹配前面的子表达式一次或多次?
: 匹配前面的子表达式零次或一次{n}
: n 是一个非负整数{n,}
: n 是一个非负整数{n,m}
: m 和 n 均为非负整数,其中n <= m
heo helo hello helllo
正则: hel*o # 可以匹配 heo helo hello helllo
正则: hel+o # 可以匹配 helo hello helllo
正则: hel?o # 可以匹配 heo helo
正则: hel{3}o # 可以匹配 helllo
正则: hel{1,}o # 可以匹配 helo hello helllo
正则: hel{0,3}o # 可以匹配 heo helo hello helllo
?
: 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的
hel hell helll
正则: hel+ # 可以匹配 hel hell helll
正则: hel+? # 只会匹配 hel hell helll中的 hel部分
.
: 匹配除 "\n" 之外的任何单个字符
hello world python
正则: .* # 可以匹配出所有单词
x|y
: 匹配 x 或 y[xyz]
: 字符集合
hello aello
正则: a|hello # 匹配 hello 和 a
正则: [a|h]ello # 匹配 hello 和 aello
范围
[xyz]
: 字符集合[^xyz]
: 字符集合取反[a-z]
: 字符范围[^a-z]
: 负值字符范围
空白符
\f
: 匹配一个换页符\n
: 匹配一个换行符\r
: 匹配一个回车符\t
: 匹配一个制表符
语法糖
\d
: 匹配一个数字字符. 相当于[0-9]
\D
: 匹配一个非数字字符. 相当于[^0-9]
\s
: 匹配任何空白字符,包括空格、制表符、换页符等等. 相当于[\f\n\t\r\v]
\S
: 匹配任何非空白字符. 相当于[^\f\n\t\r\v]
\w
: 匹配字母、数字、下划线. 相当于[A-Za-z0-9_]
\W
: 匹配非字母、数字、下划线. 相当于[^A-Za-z0-9_]
如何在python中使用正则表达式
re模块
查找
re.search
import re
test_string = 'hello'
result = re.search('l', test_string)
print(result)
运行结果:
[Running] python "g:\phpStudy\WWW\test_py\.vscode\test.py"
<_sre.SRE_Match object; span=(2, 3), match='l'>
[Done] exited with code=0 in 0.116 seconds
re.findall
import re
test_string = 'hello'
result = re.findall('l', test_string)
print(result)
运行结果:
[Running] python "g:\phpStudy\WWW\test_py\.vscode\test.py"
['l', 'l']
[Done] exited with code=0 in 0.11 seconds
替换
re.sub
import re
test_string = 'hello'
result = re.sub('l', 'm', test_string)
print(result)
运行结果:
[Running] python "g:\phpStudy\WWW\test_py\.vscode\test.py"
hemmo
[Done] exited with code=0 in 0.12 seconds