打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
正则表达式不是一天能学会的!这是我花七天整理的!希望能帮到你
userphoto

2018.12.16

关注

一.正则表达式概念

1.定义

正则表达式,又称规则表达式。(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。正则表达式(Regular Expression)是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为'元字符')。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串。

2.表达式列表

私信菜鸟007有更多的教程!

3.(?iLmsux)为分组设置模式

这里的”i”, “L”, “m”, “s”, “u”, “x”,它们不匹配任何字串,而是表示对应python中re模块当中的(re.I, re.L, re.M, re.S, re.U, re.X)的6种选项。

可以在python源码中看到:

I = IGNORECASE # 忽略大小写L = LOCALE # 字符集本地化,为了支持多语言版本的字符集使用环境U = UNICODE # 使用\w,\W,\b,\B这些元字符时将按照UNICODE定义的属性M = MULTILINE # 多行模式,改变 ^ 和 $ 的行为S = DOTALL # '.' 的匹配不受限制,包括换行符X = VERBOSE # 冗余模式,可以忽略正则表达式中的空白和#号的注释

六种模式在正则表达式中可以同时使用多个的,在 python 里面使用按位或运算符 | 同时添加多个模式如:re.compile(”, re.I|re.M|re.S)

4.反斜杠的使用

在一般的编程语言当中,反斜杠“\”代表反转义字符,在反斜杠后面加一个字符可以表示一种特定的意思,接下来列举几个常见的转义字符.

因为在正则表达式的规则当中,‘\’就是转义字符的意思,前面基本语法规则里也有说到,但是在一般的变成语言中,’\’也有转义字符的意思,所以,如果我们要是写代码的时候用到正则表达式中的’\’的时候,就需要写四个’\’,才可以代表一个真正的反斜杠字符,如:“\\\\”。“\\\\”:这里的第一个和第三个是在编程语言中起转义的作用,果:“\\”,然后在正则表达式中它在进行一次反转义就代表着一个真正的反斜杠字符了。但是在python语言中,我们可以不考虑这个问题。只需要在写好的字符串前面加一个’r’, 告诉编译器这个字符串是个原生字符串,不要转义’\’ 。例如,上个例子中的正则表达式可以使用r”\”表示。因为加上这个’r’,只是告诉python语言不转义这个字符串,但是在正则表达式中还是要符合正则表达式的规则。同样,匹配一个数字的”\d”就可以写成r”\d”。所以,在python中写正则表达式时,要养成一个前面写’r’的习惯。

5.表达式的应用与区别:

(1).^${}的区别

注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,在一个量词后面加?号使其变成惰性匹配

(2)字符集[] [^]

(3)转义符\

在正则表达式中,有很多有特殊意义的是元字符,比如\d和\s等,如果要在正则中匹配正常的'\d'而不是'数字'就需要对'\'进行转义,变成'\\'。在python中,无论是正则表达式,还是待匹配的内容,都是以字符串的形式出现的,在字符串中\也有特殊的含义,本身还需要转义。所以如果匹配一次'\d',字符串中要写成'\\d',那么正则里就要写成'\\\\d',这样就太麻烦了。这个时候我们就用到了r'\d'这个概念,此时的正则是r'\\d'就可以了。

(4)贪婪匹配

(5)非贪婪匹配

*? 重复任意次,但尽可能少重复+? 重复1次或更多次,但尽可能少重复?? 重复0次或1次,但尽可能少重复{n,m}? 重复n到m次,但尽可能少重复{n,}? 重复n次以上,但尽可能少重复

(6).*?的用法

. 是任意字符* 是取 0 至 无限长度? 是非贪婪模式。何在一起就是 取尽量少的任意字符,一般不会这么单独写,他大多用在:.*?x 就是取前面任意长度的字符,直到一个x出现

6.re函数方法总结

7.常用函数举例

(1)贪婪与非贪婪模式举例

import reexample = '
test1
test2
'greedPattern = re.compile('
.*
')notGreedPattern = re.compile('
.*?
')greedResult = greedPattern.search(example)notGreedResult = notGreedPattern.search(example)print('greedResult = %s' % greedResult.group())print('notGreedResult = %s' % notGreedResult.group())

输出结果:

(2)complie()

#描述def compile(pattern, flags=0): 'Compile a regular expression pattern, returning a pattern object.' # 生成一个正则表达式模式,返回一个Regex对象 return _compile(pattern, flags)#参数说明pattern: 正则表达式flags: 用于修改正则表达式的匹配方式,就是我们在基本语法规则中说到的(iLmsux)六种模式,默认正常模式

举例:

import repattern = re.compile(r'\d')result = pattern.match('123')print(result.group())pattern = re.compile(r'abc d', re.I|re.X)''' I = IGNORECASE # 忽略大小写 X = VERBOSE # 冗余模式,可以忽略正则表达式中的空白和#号的注释'''result = pattern.match('AbcD')print(result.group())

输出:

(3)match()

源码描述:

1. def match(pattern, string, flags=0): '''Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.''' # 在字符串的开头匹配pattern,返回Match匹配对象,如果没有不到匹配的对象,返回None。 return _compile(pattern, flags).match(string)2. def match(self, string, pos=0, endpos=-1): '''Matches zero | more characters at the beginning of the string.''' pass # 可以指定匹配的字符串起始位置#参数说明# 其他两个参数与compile()当中的意义一致string: 需要验证的字符串pos: 设定开始位置,默认0endpos: 设定结束位置,默认-1

举例:

import reresult = re.match(r'a+\d', 'aA123', re.I)print(result.group())# 输出结果为aA1 只要pattern匹配完了,则视为成功,并将匹配成功的字符串返回pattern = re.compile(r'abc d', re.I|re.X)result = pattern.match('0AbcD5', 1, 5)print(result.group())# 输出结果为AbcD 从第1个位置开始,到第5个位置之前的字符串

(4)search()

源码描述:

1. def search(pattern, string, flags=0): '''Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.''' # 大致意思与match方法相同,不同的地方在于search时整个字符串任意位置匹配,而match时从特定的位置(pos)开始向后仅匹配一次 return _compile(pattern, flags).search(string)2. def search(self, string, pos=0, endpos=-1): '''Scan through string looking for a match, and return a corresponding match instance. Return None if no position in the string matches.''' pass # 可以指定字符串的子串进行匹配#参数与match()中的一致

举例:

import repattern = re.compile(r'abc d', re.I|re.X)result = pattern.search('0A2aBcd7')print(result.group())# 输出结果为aBcd 在字符串中任意位置只要匹配到就返回结果pattern = re.compile(r'abc d', re.I|re.X)matchResult = pattern.match('0AbcD5')searchResult = pattern.search('0AbcD5')print(matchResult)print(searchResult)# matchResult的结果是None# searchResult.group()的结果结果为AbcD# 因为在pattern中第一个位置是a,但是在字符串中第一个位置是0,所以match方法在这里匹配失败

(5)group(),groups()和groupdict()

源码描述:

1.def group(self, *args): '''Return one or more subgroups of the match.''' # 返回成功匹配的一个或多个子组 pass2.def groups(self, default=None): '''Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern.''' # 以元组的格式返回所有分组匹配到的字符 pass3.def groupdict(self, default=None): '''Return a dictionary containing all the named subgroups of the match,keyed by the subgroup name.''' # 以字典的格式返回所有分组匹配到的字符 pass#参数说明:group中的*args: 如果参数为一个,就返回一个子串;如果参数有多个,就返回多个子串的元组。如果不传任何参数,和传入0一样,将返回整个匹配子串。groups中的default: 用于给那些没有匹配到的分组做默认值,它的默认值是Nonegroupdict中的default: 用于给那些没有匹配到的分组做默认值,它的默认值是None

举例:

import repattern = re.compile(r'([\w]+) ([\w]+)')m = pattern.match('Hello World Hi Python')print(m.group())# 输出结果为Hello World 第一个分组成功匹配到Hello第二个成功匹配到World 正则表达式已匹配结束print(m.group(1))# 输出结果为Hello 取第一个分组成功匹配到Helloprint(m.group(2))# 输出结果为World 取第二个分组成功匹配到Worldpattern = re.compile(r'([\w]+)\.?([\w]+)?')m = pattern.match('Hello')print(m.groups())# 输出结果为('Hello', None) 第一个元素是一个分组匹配到的Hello,因为第二个分组没有匹配到,所以返回Noneprint(m.groups('Python'))# 输出结果为('Hello', 'Python') 因为第二个分组没有匹配到,所以返回在groups中设置的默认值pattern = re.compile(r'(?P\w+) (?P\w+)')m = pattern.match('Hello Python')print(m.groupdict())# 输出结果为{'first_str': 'Hello', 'last_str': 'Python'} 默认值的用法与group

(6)findall()

源码描述:

def findall(self, string, pos=0, endpos=-1): '''Return a list of all non-overlapping matches of pattern in string.''' # 返回字符串中所有匹配成功的子串的列表, #重点:返回的是一个列表,没有group方法 pass#参数说明# 与match方法一致

举例:

import repattern = re.compile(r'\d+')m = pattern.findall('a1b2c33d4')print(m)# 输出['1', '2', '33', '4'] 查找出字符串中的所有数字m = pattern.findall('a1b2c33d4', 1, 6)print(m)# 输出['1', '2', '3'] 在'1b2c3'中查找

(7)finditer()

源码描述:

def finditer(self, string, pos=0, endpos=-1): '''Return an iterator over all non-overlapping matches for the pattern in string. For each match, the iterator returns a match object.''' # 返回字符串中所有匹配成功的子串的迭代器 pass#参数说明#与match方法一致

举例:

import repattern = re.compile(r'\d+')m = pattern.finditer('a1b2c33d4')print(m)# 输出迭代器print(next(m).group())# 依次输出匹配到的结果 1

(8)split()

源码描述:

def split(self, string, maxsplit=0): '''Split string by the occurrences of pattern.''' # 返回根据匹配到的的子串将字符串分割后成列表 pass#参数说明#maxsplit: 指定最大分割次数,不指定将全部分割。

举例:

import repattern = re.compile(r'\d+')m = pattern.split('a1b2c3d4e')print(m)# 输出['a', 'b', 'c', 'd', 'e'] 根据数字,全部分割m = pattern.split('a1b2c3d4e', 3)print(m)# 输出['a', 'b', 'c', 'd4e'] 只分割三次,后面的不进行分割

9 sub()

源码描述

def sub(self, repl, string, count=0): '''Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.''' # repl替换掉字符串中匹配到的子串,变成新的字符串返回 pass#参数说明repl: 替补内容string: 原字符串count: 替换次数,默认全部替换

举例:

import repattern = re.compile(r'\s+')text = 'Process finished with exit code 0'm = pattern.sub('-', text, 3)print(m)# 输出结果Process-finished-with-exit code 0 前三个空格被‘-’替换了

10.subn()

源码描述:

def subn(self, repl, string, count=0): '''Return the tuple (new_string, number_of_subs_made) found by replacing the leftmost non-overlapping occurrences of pattern with the replacement repl.''' # 返回一个由替换后的结果和替换的次数组成的元组 pass#参数说明与sub()参数含义一致

举例:

import repattern = re.compile(r'\s+')text = 'Process finished with exit code 0'm = pattern.subn('-', text)print(m)# 输出结果('Process-finished-with-exit-code-0', 5)

未完待续。。。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python re模块
re模块的详细解析
python正则表达式
零基础写python爬虫之神器正则表达式
Python 正则表达式学习摘要及资料
Py之re:re正则表达式库的简介、入门、使用方法之详细攻略
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服