Python-字符串解析-正则-re
Posted 北门吹雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-字符串解析-正则-re相关的知识,希望对你有一定的参考价值。
正则表达式
特殊字符序列,匹配检索和替换文本
普通字符 + 特殊字符 + 数量,普通字符用来定边界
更改字符思路
字符串函数 > 正则 > for循环
元字符 匹配一个字符
# 元字符大写,一般都是取小写的反
1. 0~9 整数 \d 取反 \D
import re example_str = "Beautiful is better than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r"\d", example_str)) print(re.findall(r"\D", example_str))
2. 字母、数字、下划线 \w 取反 \W
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘\w‘, example_str)) print(re.findall(r‘\W‘, example_str))
3. 空白字符(空格、\t、\t、\n) \s 取反 \S
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘\s‘, example_str)) print(re.findall(r‘\S‘, example_str))
4. 字符集中出现任意一个 [] 0-9 a-z A-Z 取反 [^]
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘[0-9]‘, example_str)) print(re.findall(r‘[^0-9]‘, example_str))
5. 除 \n 之外任意字符
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r".", example_str))
数量词 指定前面一个字符出现次数
1. 贪婪和非贪婪
a. 默认情况下是贪婪匹配,尽可能最大匹配直至某个字符不满足条件才会停止(最大满足匹配)
b. 非贪婪匹配, 在数量词后面加上 ? ,最小满足匹配
c. 贪婪和非贪婪的使用,是程序引起bug重大原因
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘.*u‘, example_str)) print(re.findall(r‘.*?u‘, example_str))
2. 重复指定次数 {n} {n, m}
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘\d{3}‘, example_str))
3. 0次和无限多次 *
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘.*‘, example_str))
4. 1次和无限多次 +
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘\d+‘, example_str))
5. 0次或1次 ? 使用思路: 去重
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘7896?‘, example_str))
边界匹配
1. 从字符串开头匹配 ^
2. 从字符串结尾匹配 $
正则表达式或关系 |
满足 | 左边或者右边的正则表达式
import re example_str = "Beautiful is better_ than ugly 78966828 $ \r \r\n ^Explicit is better than implicit" print(re.findall(r‘\d+|\w+‘, example_str))
组
() 括号内的正则表达式当作单个字符,并且返回()内正则匹配的内容,可以多个,与关系
Python-正则相关模块-re
1. 从字符中找到匹配正则的字符 findall()
import re name = "Hello Python 3.7, 123456789" total = re.findall(r"\d+", name) print(total)
2. 替换正则匹配者字符串 sub()
import re def replace(value): return str(int(value.group()) + 1) result_str = re.sub(r"\d", replace, name, 0) print(result_str)
匹配一个中文字符 [\u4E00-\u9FA5]
以上是关于Python-字符串解析-正则-re的主要内容,如果未能解决你的问题,请参考以下文章