Python re模块学习

这是re模块与正则的结合

re模块提供的函数

1.match  尝试在字符串的开头应用该模式,返回匹配对象,如果没有找到匹配,则为None。

1 import re
2 
3 str1 = "Why are you keeping this curiosity door locked?"
4 res = re.match('\w+y', str1)
5 print(res)

如果要获取匹配的值则需要调用group()方法:

print(res.group())

2. fullmatch  表示匹配全部字符串,返回匹配对象,如果没有找到匹配,则返回None。

 

import re

str1 = "Why are you keeping this curiosity door locked?"
res = re.fullmatch('\w+y', str1)
print(res)

import re

str1 = "Why"
res = re.fullmatch('\w+y', str1)
print(res)

3.search  匹配到第一个符合的字符串就会停止,返回匹配对象,如果没有找到匹配,则返回None。

 

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.search('\w+g', str1)
print(res)
print(res.group())

match  就相当于 re.search('^RE', string) (从头开始去匹配)

4. findall 匹配字符串中所有符合的 ,返回匹配对象(列表),如果没有找到匹配,则返回None。

 

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.findall('\w+g', str1)
print(res)

5. sub 把匹配到的字符串再用给的字符替换,然后返回新的字符串

sub(pattern, repl, string, count=0, flags=0)
import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.sub('ing', 'ed', str1)
print(res)

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.subn('ing', 'ed', str1)
print(res)

subn则会告诉你替换了多少处(返回的是一个元祖)

6. split  相当于 字符串的split的用法, 返回切割后的列表

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.split('e', str1)
print(res)

可以把(RE)用括号括起来就可以把用来切割的 字符串也包含进列表中

import re

str1 = "Why are you keeping this curiosity door locked? looking foreword"
res = re.split('(\we)', str1)
print(res)

 

7. compile 先把正则编译,如果需要很多匹配的字符串都用到同一个正则表达式,则可以用compile先把正则编译好,可以节约时间

8.finditer  可以从匹配到的列表里一个一个的获取到数据,经常与compile连用处理比较多的数据

 

 

posted @ 2019-07-13 12:50  浪上了天  阅读(1436)  评论(0编辑  收藏  举报