1,findall(pattern,string)
返回所有符合pattern的字符串,返回值是列表的格式;如果匹配有多个分组,那么列表的元素是一个元组
key="my w2014-12-12orld helLO a2015-10-10ahello"
pat=re.compile("(\d+)-(\d+)-(\d+)",re.I)
result=pat.findall(key)
print result
返回 => [('2014', '12', '12'), ('2015', '10', '10')]
2,match(pattern,string)
返回字符串中开头匹配的部分,需要从起始位置开始匹配
3,search(pattern,string)
返回字符串中第一个匹配的部分
key="my w2014-12-12orld helLO a2015-10-10ahello"
pat=re.compile("(\d{4})-(\d+)-(\d+)",re.I)
result=pat.search(key).groups()
print result
=> ('2014', '12', '12')
key = "my w2014-12-12orld helLO a2015-10-10ahello"
pat = re.compile(".*(\d{4})-(\d+)-(\d+)", re.I)
result = pat.match(key).groups()
print result
=> ('2015', '10', '10')
4,split(pattern,string) 根据pattern 出现的位置拆分string,返回一个列表
key = "my w2014-12-12orld helLO a2015-10-10ahello"
pat = re.compile("\d+-\d+-\d+", re.I)
result=pat.split(key)
print result
=> ['my w', 'orld helLO a', 'ahello']
5,sub就是一般的replace函数,只是匹配部分使用的是正则而已,返回的是字符串
p="apple|orange|banala"
key="apple are good,orange are delicious,banala are yellow"
result=re.compile(p,re.I).sub("fruit",key)
print result
=> fruit are good,fruit are delicious,fruit is yellow
返回所有符合pattern的字符串,返回值是列表的格式;如果匹配有多个分组,那么列表的元素是一个元组
key="my w2014-12-12orld helLO a2015-10-10ahello"
pat=re.compile("(\d+)-(\d+)-(\d+)",re.I)
result=pat.findall(key)
print result
返回 => [('2014', '12', '12'), ('2015', '10', '10')]
2,match(pattern,string)
返回字符串中开头匹配的部分,需要从起始位置开始匹配
3,search(pattern,string)
返回字符串中第一个匹配的部分
key="my w2014-12-12orld helLO a2015-10-10ahello"
pat=re.compile("(\d{4})-(\d+)-(\d+)",re.I)
result=pat.search(key).groups()
print result
=> ('2014', '12', '12')
key = "my w2014-12-12orld helLO a2015-10-10ahello"
pat = re.compile(".*(\d{4})-(\d+)-(\d+)", re.I)
result = pat.match(key).groups()
print result
=> ('2015', '10', '10')
4,split(pattern,string) 根据pattern 出现的位置拆分string,返回一个列表
key = "my w2014-12-12orld helLO a2015-10-10ahello"
pat = re.compile("\d+-\d+-\d+", re.I)
result=pat.split(key)
print result
=> ['my w', 'orld helLO a', 'ahello']
5,sub就是一般的replace函数,只是匹配部分使用的是正则而已,返回的是字符串
p="apple|orange|banala"
key="apple are good,orange are delicious,banala are yellow"
result=re.compile(p,re.I).sub("fruit",key)
print result
=> fruit are good,fruit are delicious,fruit is yellow