第九章 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

猜你喜欢

转载自blog.csdn.net/wshsdm/article/details/80244383