元字符具有特殊意义的专用字符。
"^"表示匹配的开始;"$"表示匹配的结束。
| 元字符 | 描述说明 | 举例 | 结果 |
| . | 匹配任意字符(除\n) | ’p\nytho\tn‘ | p,y.t,h,o,\t,n |
| \w | 匹配字母、数字、下划线 | 'python\n123' | p,y,t,h,o,n,1,2,3 |
| \W | 匹配非字母、数字、下划线 | 'python\n123' | \n |
| \s | 匹配任意空白字符 | 'python\t123' | \t |
| \S | 匹配任意非空白字符 | 'python\t123' | p,y,t,h,o,n,1,2,3 |
| \d | 匹配任意十进制数 | 'python\t123' | 1,2,3 |
限定符用于限定匹配的次数 。
| 限定符 | 描述说明 | 举例 | 结果 |
| ? | 匹配前面的字符0次或1次 | colou?r | 可以匹配color或colour |
| + | 匹配前面的字符1次或多次 | colou+r | 可以匹配colour或colouu...r |
| * | 匹配前面的字符0次或多次 | colou*r | 可以匹配color或colouu...r |
| {n} | 匹配前面的字符n次 | colou{2}r | 可以匹配colouur |
| {n,} | 匹配前面的字符最少n次 | colou{2,}r | 可以匹配colouur或colouuu...r |
| {n,m} | 匹配前面的字符最少n次,最多m次 | colou{2,4}r | 可以匹配colouur或colouuur或colouuuur |
| 其他字符 | 描述说明 | 举例 | 结果 |
| 区间字符[] | 匹配[]中所指定的字符 |
[.?!] [0-9] |
匹配标点符号点、问号、感叹号 匹配数字0,1,2,3,4,5,6,7,8,9 |
| 排除字符^ | 匹配不在[]中指定的字符 | [^0-9] | 匹配除0,1,2,3,4,5,6,7,8,9的字符 |
| 选择字符| | 用于匹配|左右的任意字符 | \d{18}|\d{15} | 匹配15位身份证或18位身份证 |
| 转义字符 | 同python中的转义字符 | \. | 将.作为普通字符使用 |
| [\u4e00-\u9fa5] | 匹配任意一个汉字 | ||
| 分组 | 改变限定符的作用 |
six|fourth (six|four)th |
匹配six或fourth 匹配sixth或fourth |
re模块python中的内置模块,用于实现python中的正则表达式操作。
| 函数 | 功能描述 |
| re.match(pattern,string,flags=0) | 用于从字符串的开始位置进行匹配,如果起始位置匹配成功,结果为Match对象,否则结果为None. |
| re.search(pattern,string,flags=0) | 用于在整个字符串中搜索第一个匹配的值,如果匹配成功,结果为Match对象,否则结果为None。 |
| re.findall(pattern,string,flags=0) | 用于在整个字符串搜索所有符合正则表达式的值,结果是一个列表类型。 |
| re.sub(pattern,repl,string,count,flags=0) | 用于实现对字符串中指定子串的替换 |
| re.split(pattern,string,maxsplit,flags=0) | 字符串中的split()方法功能相同,都是分隔字符串 |
import re # match()函数 从开始位置查找,如果存在,则返回对应的对象,反之则返回None pattern=r'\d\.\d+' # + 限定符 \d 0-9数字出现1次或多次 s='I study python 3.12 ervery day' match=re.match(pattern,s,re.I) print(match) print('*'*50) s2='3.12 I study every day' match2=re.match(pattern,s2) print(match2) print('匹配开始位置',match2.start()) print('匹配结束位置',match2.end()) print('匹配区间的位置元素',match2.span()) print('待匹配的字符串',match2.string) print('匹配的数据',match2.group()) print('*'*50) # search()函数查找的第一次匹配的对象,如果存在,则返回对应的对象。如果不存在,则返回None s3='I study python3.12 every day 3.13' pattern3=r'\d\.\d+' match3=re.search(pattern3,s3) print(match3) print('匹配开始位置',match3.start()) print('匹配结束位置',match3.end()) print('匹配区间的位置元素',match3.span()) print('待匹配的字符串',match3.string) print('匹配的数据',match3.group()) s3='I study python every day' match3=re.search(pattern3,s3) # None print(match3) print('*'*50) # findall()函数查询所有匹配的对象,返回一个列表。如果不存在,则返回一个空列表 pattern4=r'\d\.\d+' s4='3.12 python I study every day 3.10' match4=re.findall(pattern4,s4) print(match4) s4='I love you' match4=re.findall(pattern4,s4) # [] print(match4) print('*'*50) # sub()函数如果匹配到存在的子串,则替换成指定的字符串。返回一个字符串 pattern5='苹果|香蕉|橘子' s5='喜欢吃苹果,还有荔枝' new_s=re.sub(pattern5,'**',s5) print(new_s) print('*'*50) # split()函数 按照匹配的字符分隔原字符串,返回一个列表。 pattern6='[&|?]' s6='www.baidu.com?q=1&w=3' lst=re.split(pattern6,s6) print(lst)
posted on
浙公网安备 33010602011771号