Python中的正则表达式主要是由re模块提供,主要有match、search、findall、finditer等函数,这几个函数的区别:
match | 返回一个match对象,只从第一个字符开始匹配 |
search | 返回一个match对象,可以从任意字符开始匹配,只匹配第一个匹配到的字符 |
findall | 返回一个匹配列表,匹配所有可以匹配到的字符 |
finditer | 返回一个匹配生成器,匹配所有可以匹配到的字符 |
match和search函数返回的match对象有group、start、end、groups、groupdict等方法,和re、string、pos等属性。我们简单得使用以上的函数:
import re
match_m = re.match(r'python', 'python is good')
match_s = re.search(r'python', 'hi, python is good')
re_list = re.findall(r'python', 'hi, python is good, and python is easy')
re_iter = re.finditer(r'python', 'hi, python is good, and python is easy')
print(type(match_m))
print(type(match_s))
print(type(re_list))
print(type(re_iter))
# group返回一个包含匹配文本的字符串
print(match_m.group())
# start提供被查找字符串开始匹配的索引
print(match_s.start())
# end提供被查找字符串结束匹配的索引
print(match_s.end())
# groups和grooupdict用于调出正则表达式的一部分
print(match_s.groups())
print(match_s.groupdict())
# re属性包含用于匹配的正则表达式
print(match_s.re)
# string属性包含被匹配的字符串
print(match_s.string)
# pos属性被设置为匹配开始的位置
print(match_s.pos)
输出:
<class '_sre.SRE_Match'>
<class '_sre.SRE_Match'>
<class 'list'>
<class 'callable_iterator'>
python
4
10
()
{}
re.compile('python')
hi, python is good
0
其中r''正则表达式前的r字母代表的是'raw',而不是'regex',用于在字符串中不会交'\'字符解释成一个转义字符,这对于正则表达式中多种需要转义的字符写法简便了很好,是很常用的一种手法。
1. 字符组
在正则表达式中,我们用方括号[]来表示一组字符,但只匹配其中的一个。如[Pp]ython可以匹配python和Python,但不能匹配Ppython。
1.1 区间
在字符组中写[0123456789]来匹配一个数字有时候会太繁琐,我们可以用'-'符号来表示一个区间,如[0-9]就表示[01234567890],[a-z]就表示所有的小写字母,[a-zA-Z]可以匹配所有的大小写字母。
import re
res1 = re.search(r'[a-z][0-9]', 'a1')
res2 = re.search(r'[a-z][0-9]', 'b2')
print(res1)
pr