什么是正则表达式
世界上信息非常多,而我们关注的信息有限,加入我们希望只提取出关注的数据,此时可以通过一些表达式进行提取,正则表达式就是其中一种进行数据筛选的表达式。
正则表达式的通用语法
表达式 | 描述 |
() | 括起来的部分就是要提取的,可以用来分组 |
. | 匹配除换行符以外的所有单个字符 |
X* | 匹配X(单个字符)零次或多次 |
X+ | 匹配X(单个字符)一次或多次 |
.* | 匹配任意字符任意次(换行符除外) |
? | 匹配该字符前面的字符0次或1次 |
\d | 匹配数字 |
\b | 匹配单词的开始或结束 |
\w | 匹配数字或者字母或下划线或汉字 |
{n} | 表示匹配n个字符 |
{n,m} | 表示匹配n-m个字符 |
\s | 匹配空格 |
[] | 表示范围,如[0-9a-zA-Z]表示匹配数字小写字母和大写字母 |
^ | 表示匹配以某元素开头,该字符在[]中如[^0-2],表示不包含0-2 |
$ | 表示匹配以某元素结尾 |
A|B | 匹配A或者B |
re模块
在Python中,使用内置的re模块来使用正则表达式,正则表达式使用\对特殊的字符进行转义,如匹配“baidu.com”,我们需要使用正则表达式"baidu\.com",但是Python的\本身也需要\转义,因此上面的正则表达式使用Python应该写成"baidu\\.com",很不方便,我们可以使用Python的原始字符串,只需要加上r前缀,这样的话,上面的正则表达式可以写成:
1 r"baidu.com"
re模块的使用步骤一般为:
1)使用compile函数将正则表达式的字符串形式编译为一个Pattern对象。
2)通过Pattern对象提供的方法对文本进行查找,获得匹配的结果(Match对象)。
3)使用Match对象提供的属性和方法获得信息,然后根据需要进行其他操作。
compile函数
compile函数用于编译正则表达式,生成Pattern对象。
1 compile(pattern, flags=0)
说明:pattern是一个正则表达式,flag是匹配模式,如忽略大小写等。
1 import re 2 3 # 将正则表达式编译成Pattern对象 4 pattern = re.compile("\d+")
Pattern对象的常用方法有:match(),search(),findall(),finditer(),split(),sub(),subn()。
1)match方法
该方法用于查找字符串的头部,它只要找到了一个匹配的结果就返回。
1 match(string, pos=0, endpos=-1)
说明:string是待匹配的字符串,pos和endpos指定字符串的起始和终点的位置,当不指定时,默认从头部开始匹配,当匹配成功时,返回Match对象。
import re
pattern = re.compile("\\d+")
match = pattern.match("aaa123bbb123ccc123")
print(match) # None
match = pattern.match("aaa123bbb123ccc123", 3, 6)
print(match) # <_sre.SRE_Match object; span=(3, 6), match='123'>
print(match.group()) # 123,返回匹配的字符串,如果需要获得整个匹配的子串时,可以使用group()或者group(0)
print(match.start()) # 3,返回匹配的子串在整个字符串的起始位置
print(match.end()) # 6,返回匹配的子串在整个字符串的结束位置
print(match.span()) # (3, 6),返回(start(),end())
2)search()方法
该方法用于查找字符串的任何位置,它只要找到一个匹配的结果就返回。
1 search(string, pos=0, endpos=-1):
说明:string是带匹配的字符串,pos和endpos分别为字符串的起始和结束位置,当匹配成功时返回Match对象,匹配不成功时返回None。
pattern = re.compile("\\d+")
match = pattern.search("aaaa1111bbbb2222cccc3333")
print(match) # <_sre.SRE_Match object; span=(4, 8), match='1111'>
match = pattern.search("aaaa1111bbbb2222cccc3333", 3, 6)
print(match) # <_sre.SRE_Match object; span=(4, 6), match='11'>
print(match.group()) # 11,返回匹配的字符串,如果需要获得整个匹配的子串时,可以使用group()或者group(0)
print(match.start()) # 4,返回匹配的子串在整个字符串的起始位置
print(match.end()) # 6,返回匹配的子串在整个字符串的结束位置
print(match.span()) # (4, 6),返回(start(),end())
3)findall()方法
该方法返回所有匹配的结果。
1 findall(string, pos=0, endpos=-1)
说明:string表示需要匹配的字符串,pos和endpos表示匹配字符串的起始和结束位置,匹配成功,返回匹配的列表,匹配不成功,返回空列表。
import re
pattern = re.compile("\\d+")
match = pattern.findall("aaaa1111bbbb2222cccc3333")
print(match) # ['1111', '2222', '3333']
4)finditer()方法
1 finditer(string, pos=0, endpos=-1)
说明:该方法表示匹配所有的字符串,pos和endpos表示匹配字符串的起始和结束位置。
该方法返回所有匹配的字符串,但是它返回的是一个迭代器,通过该迭代器我们可以访问匹配的每一个字符串。
import re
pattern = re.compile("\\d+")
result_iter = pattern.finditer("aaaa1111bbbb2222cccc3333")
for result in result_iter:
print("找到的字符串{0},位置是{1}".format(result.group(), result.span()))
# 找到的字符串1111,位置是(4, 8)
# 找到的字符串2222,位置是(12, 16)
# 找到的字符串3333,位置是(20, 24)
5)split()方法
1 split(string, maxsplit=0)
说明:该方法表示将能够匹配的子串切割,string表示需要匹配的字符串,maxsplit表示最大的分割次数,不指定即为全部分割。
import re
# 将正则表达式编译成Pattern对象
pattern = re.compile("[,;\s]+") # 匹配, ; 空格一次或多次
l = pattern.split("a,b;c d", 2)
print(l) # ['a', 'b', 'c d']
6)sub()方法
1 sub(repl, string, count=0)
说明:该方法用来替换。
repl如果为字符串,会使用repl替换字符串中的每一个匹配的子串,并且返回替换后的字符串;如果为函数,则该函数应该只接收一个Match对象,并且返回一个字符串用于替换。
count用于指定替换次数。
# 将正则表达式编译成Pattern对象
p = re.compile(r'(\w+) (\w+)')
s = 'test aaa, test bbb'
def func(m):
return 'hei' + ' ' + m.group(2)
print(p.sub(r'hello world', s)) # ('hello world, hello world'),使用hello world替换
print(p.sub(r'\2 \1', s)) # ('aaa test, bbb test'),引用分组
print(p.sub(func, s)) # ('hei aaa, hei bbb'),替换全部
print(p.sub(func, s, 1)) # ('hei aaa, test bbb'),最多只替换一次
7)subn()方法
1 subn(repl, string, count=0)
该方法也是用于替换,返回一个元组,元组有两个元素,第一个和使用sub方法返回的结果一样,另一个表示替换的次数。
# 将正则表达式编译成Pattern对象
p = re.compile(r'(\w+) (\w+)')
s = 'test aaa, test bbb'
def func(m):
return 'hei' + ' ' + m.group(2)
print(p.subn(r'hello world', s)) # ('hello world, hello world', 2),使用hello world替换
print(p.subn(r'\2 \1', s)) # ('aaa test, bbb test', 2),引用分组
print(p.subn(func, s)) # ('hei aaa, hei bbb', 2),替换全部
print(p.subn(func, s, 1)) # ('hei aaa, test bbb', 1),最多只替换一次