match函数只匹配字符串中开头的字符
import re str = 'Holle World! Holle World!' match = re.match('Ho', str) match.group() 'Ho' match.start() 0 match.end() 2 match.span() (0, 2)
下面是match的参数:
re.match(pattern, string, flags=0)
flags是正则表达式修饰符,一般不用,后面不会再解释,可去正则表达式修饰符篇查看
findall函数匹配文本中所有的字符
import re str = 'Holle World! Holle World!' findall = re.findall('ll', str) findall ['ll', 'll']
re.findall(pattern, string, flags=0)
同上
search函数只匹配一次文本,匹配后返回
import re str = 'Holle World! Holle World!' search = re.search('ol', str) search.group() 'ol' search.span() (1, 3) search.start() 1 search.end() 3
re.search(pattern, string, flags=0)
同上
sub函数用指定的字符串去替换文本中的指定内容
import re str = 'Holle World! Holle World!' sub = re.sub('Holle', 'Hi', str) sub 'Hi World! Hi World!'
re.sub(pattern, repl, string, flags=0)
字符 | 含义 |
---|---|
pattern | 文本中的指定内容 |
repl | 指定的字符串 |
string | 文本 |
compile 函数用于编译正则表达式,生成一个正则表达式的对象,供 match和 search 这两个函数使用。
import re str = 'Holle World! Holle World!' compile = re.compile('Ho') compile.search(str) <re.Match object; span=(0, 2), match='Ho'> compile.match(str) <re.Match object; span=(0, 2), match='Ho'> compile.search(str, 1, 25) <re.Match object; span=(13, 15), match='Ho'> compile.match(str, 1, 25) # 没有返回值 compile.match(str, 13, 25) <re.Match object; span=(13, 15), match='Ho'>
re.compile(pattern[, flags])
PS:该篇内容是对re中五个函数的一些粗略的介绍,更多内容往后继续更新!