正则表达式常用函数
-
re.match函数 尝试从字符串的开始位置匹配。
re.match(pattern, string, flags)
第一个参数为正则表达式,匹配成功返回match,否则返回None。第二个参数为要匹配的字符串。第三个参数为是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配。 -
re.search函数
re.search(pattern, string, flags)
函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
参数的含意与re.match相同
re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。 -
re.split函数
可以使用re.split来分割字符串,例:re.split(r’\s+’, text);将字符串按空格分割成一个单词列表。 -
re.findall 函数
可以获取字符串中所有匹配的字符串。如:re.findall(r’\woo\w’, text);获取字符串中,包含’oo’的所有单词。 -
re.compile函数
可以把正则表达式编译成一个正则表达式对象。 -
re.sub函数
re.match()函数实例
import re
string="helloworld"
p="Low"
result=re.match(p,string,re.I)
print(result)
None
所要匹配的第一个字符为"L",用match函数很显然匹配失败,match函数从字符串的首字符进行匹配。
re.search()函数实例
import re
string="helloworld"
p="Low"
result=re.search(p,string,re.I)
print(result)
<re.Match object; span=(3, 6), match='low'>
匹配成功,search函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回。
全局匹配
格式:compile§.findall(string)
实例:
import re
string='''helloworldowdorwwoao
wangyi'''
p="o.*?o"
result=re.compile(p).findall(string)
print(result)
['owo', 'owdo', 'oao']
全部匹配了出来。