第九章 python正则表达式

什么是正则表达式

正则表达式就是记录文本规则的代码


基本用法

\: 将下一个字符标记为一个特殊字符.

 
 
  1. d # 普通字符
  2. \d # 0-9 正整数
  3. s # 普通字符
  4. \s # 空白符,比如\t,\n

定界符

^: 匹配输入字符串的开始位置 
$: 匹配输入字符串的结束位置

 
 
  1. 正则: ^123.*123$ # 匹配123hello123

\b: 匹配一个单词边界,也就是指单词和空格间的位置

 
 
  1. teacher Li
  2. 正则: er\b # 可以匹配出er

\B: 匹配非单词边界

 
 
  1. verb
  2. 正则: er\B # 可以匹配出er

个数/次数

*: 匹配前面的子表达式零次或多次 
+: 匹配前面的子表达式一次或多次 
?: 匹配前面的子表达式零次或一次 
{n}: n 是一个非负整数 
{n,}: n 是一个非负整数 
{n,m}: m 和 n 均为非负整数,其中n <= m

 
 
  1. heo helo hello helllo
  2. 正则: hel*o # 可以匹配 heo helo hello helllo
  3. 正则: hel+o # 可以匹配 helo hello helllo
  4. 正则: hel?o # 可以匹配 heo helo
  5. 正则: hel{3}o # 可以匹配 helllo
  6. 正则: hel{1,}o # 可以匹配 helo hello helllo
  7. 正则: hel{0,3}o # 可以匹配 heo helo hello helllo

?: 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 后面时,匹配模式是非贪婪的

 
 
  1. hel hell helll
  2. 正则: hel+ # 可以匹配 hel hell helll
  3. 正则: hel+? # 只会匹配 hel hell helll中的 hel部分

.: 匹配除 "\n" 之外的任何单个字符

 
 
  1. hello world python
  2. 正则: .* # 可以匹配出所有单词

x|y: 匹配 x 或 y 
[xyz]: 字符集合

 
 
  1. hello aello
  2. 正则: a|hello # 匹配 hello 和 a
  3. 正则: [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

 
  1. import re
  2. test_string = 'hello'
  3. result = re.search('l', test_string)
  4. print(result)

运行结果:

 
  1. [Running] python "g:\phpStudy\WWW\test_py\.vscode\test.py"
  2. <_sre.SRE_Match object; span=(2, 3), match='l'>
  3. [Done] exited with code=0 in 0.116 seconds

re.findall

 
  1. import re
  2. test_string = 'hello'
  3. result = re.findall('l', test_string)
  4. print(result)

运行结果:

 
  1. [Running] python "g:\phpStudy\WWW\test_py\.vscode\test.py"
  2. ['l', 'l']
  3. [Done] exited with code=0 in 0.11 seconds
替换

re.sub

 
  1. import re
  2. test_string = 'hello'
  3. result = re.sub('l', 'm', test_string)
  4. print(result)

运行结果:

 
  1. [Running] python "g:\phpStudy\WWW\test_py\.vscode\test.py"
  2. hemmo
  3. [Done] exited with code=0 in 0.12 seconds
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值