match
从开头进行匹配,不匹配报错
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
search
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).search(string)
注意点:
1、search是从整个字符串里查找
findall的注意点:
1、将字符串中所有符合要求的字符返回
2、返回的结果是一个列表类型
3、如果没有符合条件的,返回的是一个空列表
4、一般findall比search和match用的多
sub
ret = re.sub('\d{2}','19','age is 18,phone is 123',1)
print(ret)
#替换字符串'age is 18,phone is 123'中的俩位数字为19,替换次数为1
split
ret = re.split(' |,','age is 18,phone is 123')
print(ret)
#把字符串以|分割出来
贪婪匹配与非贪婪匹配
print(’######################################’)
re1 = re.match(’\d*?’,‘123456789’)
re1 = re.match(’\d+?’,‘123456789’)
print(re1.group())
注意点:
1、默认的状态是贪婪匹配,尽可能多的去匹配字符个数
2、在多个匹配符号后面,比如:* + {m,n}