re模块

1、正则表达式的概念

正则表达式是用来简洁表达一组字串的表达式。

正则表达式的语法

re库的基本使用

原生字符合以r开头,反指不包含转义符的字符串

import re

match1 = re.search(r'[1-9]d{5}', 'BIT 100081')
if match1:
    print(match1.group(0))  #100081

match2 = re.match(r'[1-9]d{5}', "100081 BIT ")
if match2:
    print(match2.group(0)) #100081

match3 = re.findall(r'[1-9]d{5}','100081 BIT  BIT 100084')
print(match3) #['100081', '100084']

s = re.split(r'[1-9]d{5}','BIT100081 BIT100084')
print(s)#['BIT', ' BIT', '']

s1 = re.split(r'[1-9]d{5}','BIT100081 BIT100084',maxsplit=1)
print(s1)#['BIT', ' BIT100084']

for i in re.finditer(r'[1-9]d{5}','BIT100081 BIT100084'):
    if i:
        print(i.group(0)) #100081 100084

r = re.sub(r'[1-9]d{5}', ':zcode', 'BIT100081 BIT100084')
print(r) #BIT:zcode BIT:zcode

re库的Match对象

import re

match1 = re.search(r'[1-9]d{5}', 'BIT 100081')
print(match1.string) #BIT 100081
print(match1.re) #re.compile('[1-9]\d{5}')
print(match1.pos) #0
print(match1.endpos) #10
print(match1.group(0)) #100081
print(match1.start()) #4
print(match1.end()) #10
print(match1.span()) #(4, 10)

re库的贪婪匹配和最小匹配

re库默认是贪婪匹配,输出匹配到的最长度符串

import re

match1 = re.search(r'py.*n', 'pyfdjklafjn')
if match1:
    print(match1.group(0)) #pyfdjklafjn

如何输出最小度符串

import re

match1 = re.search(r'py.*?n', 'pyfdjklafjn')
if match1:
    print(match1.group(0)) #pyfn

原文地址:https://www.cnblogs.com/jp-mao/p/6702019.html