正则表达式(一)
-
re.search(pattern,string,falgs=0),在一个字符串中匹配正则表达式的第一个位置,返回match对象
-
re.match(pattern,string,flags=0),从一个字符串的开始位置起匹配正则表达式,返回match对象 # re.findall(pattern,string,flags=0),搜索字符串,以列表类型返回全部匹配的子串 #
-
re.finditer(pattern,string,flags=0),搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象
-
re.split(pattern,string,maxsplit,flags=0)将一个字符串按照正则表达式匹配结果分割,返回列表类型,maxsplit:最大分割数,剩余部分作为最后一个元素输出
-
re.sub(pattern,repl,string ,count=0,flags=0), 在一个字符串中替换所有匹配正则表达式的子串,返回替换后的字符串
import re
ss = 'I love you, do you?'
res = re.search(r'(\w+)(,)', ss)
print(res)
print(res.group(0))
print(res.group(1))
print(res.group(2))
输出结果:
ss_tosplit = 'I love you, do you?'
res = re.split(r'\W+', ss_tosplit)
print(res)
res = re.split(r'\W+', ss_tosplit, maxsplit=1)
print(res)
res = re.sub(r'(\w+)(,)', 'her,', ss)
print(res)
输出结果:
subn方法与sub一样,但是还需返回替换的次数
res = re.subn(r'(\w+)(,)', 'her,', ss)
print(res)
ss = 'I love you, do you?'
res1 = re.search(r'(\w+)', ss)
res2 = re.findall(r'(\w+)', ss)
print(res1.group())
print(res2)
pt = re.compile(r'(\w+)')
ss = 'Another kind of calling'
res = pt.findall(ss)
print(res)