Python 正则表达式
正则表达式是对字符串提取的一套规则,把这个规则用正则里面的特定语法表达出来,去匹配满足这个规则的字符串。
python 中 re模块提供了正则表达式的功能,常用的有四个方法(match、search、findall)都可以用于匹配字符串
一、match
1、匹配字符串
re.match() 必须从字符串开头匹配! match 方法尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match() 就返回none。
主要参数如下:
re.match(pattern, string)
# pattern 匹配的正则表达式
# string 要匹配的字符串
import re
a = re.match('test','testasdtest')
print(a) # 返回一个匹配对象
print(a.group()) # 返回 test,获取不到则报错
print(a.span()) # 返回匹配结果的位置,左闭右开区间
print(re.match('test','atestasdtest')) # 返回 None
re.match() 方法返回一个匹配的对象,而不是匹配的内容。如果需要返回内容则需要调用 group()。通过调用 span() 可以获得匹配结果的位置。而如果从起始位置开始没有匹配成功,即便其他部分包含需要匹配的内容,re.match() 也会返回None。
2、单字符匹配
以下字符,都匹配单个字符数据。且开头(从字符串 0 位置开始)没匹配到,即使字符串其他部分包含需要匹配的内容,.match 也会返回 none
. 匹配任意一个字符
使用几个点号就代表几个字符
import re
a = re.match('..','testasdtest')
print(a.group()) # 输出te
b = re.match('ab.','testasdtest')
print(b) # 返回 none,因为表达式是以固定的 ab 开头然后跟上通配符. 所以必须要先匹配上ab才会往后进行匹配
\d 匹配数字
一个 \d 代表一个数字。开头没匹配到,即使字符串其他部分包含需要匹配的内容,.match 也会返回 none
import re
a = re.match('\d\d','23es12testasdtest')
print(a)
b = re.match('\d\d\d','23es12testasdtest')
print(b) # 要求匹配三个数字,匹配不到返回 none
c = re.match('\d','es12testasdtest')
print(c) # 起始位置没有匹配成功,一样返回 none
\D 匹配非数字
开头没匹配到,即使字符串其他部分包含需要匹配的内容,.match 也会返回 none
import re
a = re.match('\D','23es12testasdtest')
print(a) #开头为数字所以返回none
b = re.match('\D\D','*es12testasdtest')
print(b) #返回*e
\s 匹配特殊字符,如空白,空格,tab等
import re
print(re.match('\s',' 23es 12testasdtest')) #匹配空格
print(re.match('\s',' 23es 12testasdtest')) #匹配tab
print(re.match('\s','\r23es 12testasdtest')) #匹配\r换行
print(re.match('\s','23es 12testasdtest')) #返回none
\S 匹配非空白
import re
print(re.match('\S',' 23es 12testasdtest')) #返回none
print(re.match('\S','\r23es 12testasdtest')) #none
print(re.match('\S','23es 12testasdtest'))
\w 匹配单词、字符,如大小写字母,数字,_ 下划线
import re
print(re.match('\w','23es 12testasdtest')) #返回none
print(re.match('\w\w\w','aA_3es 12testasdtest')) #返回none
print(re