表示任何单个字符
字符集,对单个字符给出取值范围
字符非集,对单个字符给出排除范围
前一个字符0或无限次扩展
前一个字符1或无限次扩展
前一个字符0或1次扩展
左右表达式任意一个
扩展前一个字符m次
扩展前一个字符m至n次
开头
结尾
代表一个分组,内部可以用|
数字,等价于[0-9]
单词字符,等价于[0-9a-zA-Z]
def test_search():
pattern = re.compile(r'[1-9]\d{5}')
match = pattern.search('BIT 1000040922')
print('匹配的字符串:'+match.group(0))
print('待匹配的文本:'+match.string)
print('使用的正则表达式对象:'+str(match.re))
print('搜索文本的开始位置:'+str(match.pos))
print('搜索文本的结束位置:'+str(match.endpos))
print('匹配字符串的开始位置:'+str(match.start()))
print('匹配字符串的结束位置:'+str(match.end()))
print(str(match.span()))
2. re.match(pattern, string, flags=0)
从一个字符串开始位置起匹配正则表达式,返回match。
注意: match函数只检测RE是不是在string的开始位置匹配,而search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none。
def test_match():
pattern = re.compile(r'[1-9]\d{5}')
match = pattern.match('1234560922 BIT')
print('匹配的字符串:'+match.group(0))
print('待匹配的文本:'+match.string)
print('使用的正则表达式对象:'+str(match.re))
print('搜索文本的开始位置:'+str(match.pos))
print('搜索文本的结束位置:'+str(match.endpos))
print('匹配字符串的开始位置:'+str(match.start()))
print('匹配字符串的结束位置:'+str(match.end()))
print(str(match.span()))
3. re.findall(pattern, string, flags=0)
搜索字符串,以列表类型返回全部匹配子串。
def test_findall():
pattern = re.compile(r'[1-9]\d{5}')
list = pattern.findall('123456 567890 BIT')
print(list)
4. re.split(pattern, string, flags=0, maxsplit=0)
返回list,将一个字符串按照正则表达式匹配结果进行分割,maxsplit为最大分割数,剩余部分作为一个整体输出。
def test_split():
pattern = re.compile(r'[1-9]\d{5}')
list = pattern.split('123456 567890 BIT')
print(list)
def test_split():
pattern = re.compile(r'[1-9]\d{5}')
list = pattern.split('123456 567890 BIT',maxsplit=1)
print(list)
5. re.finditer(pattern, string, flags=0)
搜索字符串,返回匹配结果迭代类型,每个迭代元素是match对象。
def test_finditer():
pattern = re.compile(r'[1-9]\d{5}')
match_iter = pattern.finditer('123456 567890 BIT')
for match in match_iter:
print('匹配的字符串:'+match.group(0))
print('待匹配的文本:'+match.string)
print('使用的正则表达式对象:'+str(match.re))
print('搜索文本的开始位置:'+str(match.pos))
print('搜索文本的结束位置:'+str(match.endpos))
print('匹配字符串的开始位置:'+str(match.start()))
print('匹配字符串的结束位置:'+str(match.end()))
print(str(match.span()))
6. re.sub(pattern, repl, string, count=0, flags=0)
替换匹配pattern的子串,返回新字符串。count为最大替换次数,repl为替换字符串。
def test_sub():
pattern = re.compile(r'[1-9]\d{5}')
new_str = pattern.sub('替换字符串','123456 567890 BIT')
print(new_str)
match对象的属性:
def test_group():
a = "123abc456"
print (re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)) #123abc456,返回整体
print (re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)) #123
print (re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)) #abc
print (re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)) #456
可以看出,正则表达式按照数字,字母,数字的顺序来获取相应字符串,那么分别就是“数字(group(1)) — 字母(group(2))— 数字(group(3))”的对应关系,其中,group(0)和group()效果相同,均为获取取得的字符串整体。
6. start() 匹配字符串在string中的开始位置
7. end() 匹配字符串在string中的结束位置
8. span() 返回(start(), end())
Re默认采用贪婪匹配原则,也就是会返回满足pattern的最大匹配长度的子串,但在实际开发中我们往往只需要子串的一部分信息,而不是全部,所以我们可以在操作符?的形式来表示最小匹配:
总结:只要长度输出可能不同的,都可以在操作符后面加?变成最小匹配。