什么是正则表达式?

正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),用于字符串的 匹配 和 提取 等操作。正则表达式在所有编程语言中都是通用的。

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:1097524789

匹配模式

匹配单个字符


. [ ] \d \D \s \S \w \W


匹配多个字符


* + ? {m} {m,n}


匹配字符串首尾:

在正则表达式的首部添加 ^ ,意味着待匹配的字符串从首部就要和正则式匹配。类似的,正则式尾部添加 $ ,表示待匹配的字符串从尾部需和正则式匹配。


^ $


常用的正则表达式: https://c.runoob.com/front-en...

匹配分组

利用分组, 可以提取字符串中想要的指定内容。用括号 () 括起来的正则表达式表示一个分组,通过 group() 函数可获取分组中的字符串。例子:


# 匹配电话号码, 匹配模式中有两个分组:(\d{3})、(\d{3,8})
>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')  
>>> m
<_sre.SRE_Match object; span=(0, 9), match='010-12345'>
>>> m.group(0)  # 用group函数可以提取匹配的部分
'010-12345'
>>> m.group(1)  # group(1)表示第一个分组
'010'
>>> m.group(2)  # group(2)表示第一个分组
'12345'


如果想判断字符串中 是否具有规律相同的多个子串 时, 可以采用分组:

例如,正则表达式 <(\w*)>.*<(/\1)> 可以匹配 <h1>fadsfas</h1> ,不能匹配 <h1>fadsfas</h2> 。

当分组个数过多时,可以给分组起别名,在同一个正则表达式中重复引用该分组。

  • 分组起别名: (?P<name>___) 其中 ___ 填写分组内的正则式
  • 引用别名为name的分组: (?P=name)

re模块

在Python中,re模块已为我们实现了正则表达式的相关操作:

  • re.match() : 从头开始匹配,可以利用分组获得我们想要的子串。用法见上文。
  • re.search() : 无需从头开始匹配,只返回 匹配的第一个子字符串 。
  • re.findall() : 找到字符串中 所有匹配的字符串 ,与 search() 不同, findall() 直接返回一个list。
  • re.sub() : 利用正则表达式将匹配到的字符串 批量替换 。
  • re.split() :利用正则表达式 分割字符串 ,返回一个list。

例子:


# re.search()
In [7]: ret = re.search(r"hello", "hello world! hello world!")
In [8]: ret.group()
Out[8]: 'hello'

# re.findall()
In [9]: ret = re.findall(r"hello", "hello world! hello world!")
In [10]: print(ret)
['hello', 'hello']

# re.sub()
In [15]: ret = re.sub(r"hello","bye", "hello world! hello world!")
In [16]: ret
Out[16]: 'bye world! bye world!'

# re.split()
In [12]: ret = re.split(r":| ","hello:YMN 25 shenyang")  # 按:或空格分割字符串
In [13]: ret
Out[13]: ['hello', 'YMN', '25', 'shenyang']