python正则表达式 目录: 1.用正则表达式查找特定信息 2.用正则表达式分割、替换字符串
1.用正则表达式查找特定信息 1.1最基本match search findall(常用) match: match匹配以'xxx'开头的字符串,若不是开头的,尽管属于str内,则无法匹配 如果匹配则返回匹配的对象以及条件 代码如下: import restr='''dd发达的bcfdsfd4235 ddm mM433dggfhg dm割符号分割 各个 24 432'''print(re.match('dd',str)) #match匹配以'xxx'开头的字符串,若不是开头的,尽管属于str内,则无法匹配,如果匹配则返回匹配的对象以及条件print(re.match('dd',str).span()) #span得到匹配字符的位置 search: import restr='''dd发达的bcfdsfd4235 ddm mM433dggfhg dm割符号分割 各个 24 432'''print(re.search('43',str)) #只匹配一次 #<_sre.SRE_Match object; span=(29, 31), match='43'>print(re.search('43',str).span()) #(29, 31)print(re.search('43',str).group()) #group得到匹配字符的值 '43' findall: 语法: import restr='''dd发达的bcfdsfd4235 ddm mM433dggfhg dm割符号分割 各个 24 432'''print(re.findall('dd',str)) #findall得到所有匹配条件的字符(列表形式)print(re.findall('[a-d1-4]',str)) #[],只要匹配[]其中一个即可print(re.findall('(dd|43)',str)) #(),可以匹配多个字符#任意汉字[\u4e00-\u9fa5]+print(re.findall(r'[\u4e00-\u9fa5]+',str))print(re.findall(r'\d',str)) #\d匹配任意数字print(re.findall(r'\d{1,2}',str)) #匹配1~2个数字print(re.findall(r'\w',str)) #\w 数字、字母、汉字、下划线print(re.findall(r'\s',str)) #匹配任何空白字符:[<空格>\t\r\n\f\v]print(re.findall('.',str)) #.匹配任意字符print(re.findall(r'\d$',str)) #$匹配字符串末尾(以数字结尾),在多行模式中匹配每一行的末尾print(re.findall(r'^\d',str)) #^匹配以数字开头print(re.findall(r'\d+',str)) #+匹配一个字符1次或无限次print(re.findall(r'\d*',str)) #*匹配一个字符0或多次print(re.findall(r'\d?',str)) #?匹配一个字符0次或1次print(re.findall(r'\d.+',str)) #默认为贪婪模式print(re.findall(r'\d.+?',str)) #?把模式改为非贪婪模式 标志位: import restr='''dd发达的bcfdsfd4235 ddm mM433dggfhg dm割符号分割 各个 24 432'''print(re.findall('m',str,re.I)) #re.I忽略大小写print(re.findall(r'\d.',str,re.S)) #re.S匹配包括换行在内的所有字符print(re.findall(r'\d$',str,re.M)) #re.M多行匹配print(re.findall(r'^\d',str,re.M)) #^匹配字符串开头 分组: #分组import restr='''dd发达的bcfdsfd4235 ddm mM433dggfhg dm割符号分割 各个 24 432'''print(re.findall(r'\d(.)(\d)',str,re.S)) #以分组呈现,只显示带括号的内容print(re.search(r'\d(.)(\d)',str,re.S))print(re.search(r'\d(.)(\d)',str,re.S).group(0)) #原始字符串 '423'print(re.search(r'\d(.)(\d)',str,re.S).group(1)) #第一个子串 '2'print(re.search(r'\d(.)(\d)',str,re.S).group(2)) #第二个子串 '3'print(re.search(r'\d(.)(\d)',str,re.S).groups()) #所有的子串 ('2','3') 2.用正则表达式分割、替换字符串 re.sub(pattern, repl, string, count=0, flags=0) 第一个参数:规则 import restr='''ASDSF4234ffgfhgh3454阿桑的歌dd32435 66 GBJ'''#预编译s1=re.compile(r'\d')print(s1.search(str,10).group()) #search(str,10),从第10为开始匹配print(s1.findall(str,3,12))#splitprint(str.split('4'))print(re.split('\d+',str))s3=re.compile(r'\d+')print(s3.split(str))print(s3.split(str,1)) #只分割1次#sub#第一个参数:规则 #第二个参数:替换后的字符串 #第三个参数:字符串 #第四个参数:替换个数。默认为0,表示每个匹配项都替换print(re.sub('5','ss',str)) #把5替换成sss4=compile(r'\d+')m4=re.compile(r'\d+')print(m4.sub(' ',astr)) #把数字替换成空格print(m4.sub(' ',astr,2)) #替换两次#小写变大写def f3(m): return m.group().upper()print(re.sub(r'[a-z]',f3,astr)) |
|