python 常用的正则表达式处理函数

常用的功能函数包括:match、search、findall、sub

1、re.match()函数
函数语法:

re.match(pattern, string, flags=0)

1 def match(pattern, string, flags=0):
2     """Try to apply the pattern at the start of the string, returning
3     a match object, or None if no match was found."""
4     return _compile(pattern, flags).match(string)

函数参数说明:

pattern:匹配的正则表达式
string:要匹配的字符串
flag:标志位,用于控制正则表达式的匹配方式(是否匹配大小写、多行匹配等)

作用:match()函数只在字符串的开始位置尝试匹配正则表达式,即从位置0开始匹配。如果匹配成功,则返回一个匹配的对象;如果字符串开始不符合正则表达式,则匹配失败,函数返回None。

1 import  re
2 test = 'http://news.163.com/17/0624/10/CNMHVBJP0001899N.html'
3 print(re.match(r'http',test)) # <_sre.SRE_Match object; span=(0, 4), match='http'>
4 print(re.match(r'news',test)) # None

2、re.search()函数

函数语法:

1 re.search(pattern, string[, flags])

1 def search(pattern, string, flags=0):
2     """Scan through string looking for a match to the pattern, returning
3     a match object, or None if no match was found."""
4     return _compile(pattern, flags).search(string)

re.search()匹配整个字符串,直到找到第一个匹配的,如果字符串中没有匹配的,则返回None。

1 import  re
2 test = 'I am a loving child to learn.'
3 print(re.search(r'I',test)) # <_sre.SRE_Match object; span=(0, 1), match='I'>
4 print(re.search(r'learn',test)) # <_sre.SRE_Match object; span=(23, 28), match='learn'>
5 print(re.search(r'alina',test)) # None

3、re.sub()函数

函数语法:

1 re.sub(pattern,repl,string,count,flags)


1 def sub(pattern, repl, string, count=0, flags=0):
2     """Return the string obtained by replacing the leftmost
3     non-overlapping occurrences of the pattern in string by the
4     replacement repl.  repl can be either a string or a callable;
5     if a string, backslash escapes in it are processed.  If it is
6     a callable, it's passed the match object and must return
7     a replacement string to be used."""
8     return _compile(pattern, flags).sub(repl, string, count)

函数参数说明:

pattern:匹配的正则表达式
repl:替换的字符串
String:要被查找替换的原始字符串
count:匹配后替换的最大次数,默认0表示途欢所有的匹配

re.sub()函数用于替换字符串中的匹配项。


1 import re
2 test = 'I am a loving child to learn.'
3 print(re.sub(r'child','MMMMM',test)) # 替换字符串,将child 替换成MMMMM

4、re.findall()函数

函数语法:

1 re.findall(pattern,string,flags)

1 def findall(pattern, string, flags=0):
2     """Return a list of all non-overlapping matches in the string.
3 
4     If one or more capturing groups are present in the pattern, return
5     a list of groups; this will be a list of tuples if the pattern
6     has more than one group.
7 
8     Empty matches are included in the result."""
9     return _compile(pattern, flags).findall(string)

re.findall()可以获取字符串中所有匹配的字符串

1 import re
2 test = '<a href="http://www.educity.cn/zhibo/" target="_blank">直播课堂</a>'
3 print(re.findall(r'<a href="(.*)" target="_blank">(.*)</a>',test)) #[('http://www.educity.cn/zhibo/', '直播课堂')]
发布了16 篇原创文章 · 获赞 3 · 访问量 6677

猜你喜欢

转载自blog.csdn.net/chilitian/article/details/84309459