JiaoYuan's Blog

正则表达式

Python 使用正则表达式的一些知识。

Python 调用正则表达式

Python 中使用正则表达式需要先导入 re 模块并且定义正则表达式然后再进行通过 re 模块的函数调用

>>> import re
>>> p = r'\w+@gmail\.com'
>>> email = 'hieroglyphs@gmail.com'
>>> m = re.match(p, email)
>>> print(m)
<re.Match object; span=(0, 21), match='hieroglyphs@gmail.com'>

返回非空的 Match 对象则说明匹配成功,返回 None 则匹配失败

Python 中 re 模块常用的函数(p 为正则表达式,string 为字符串):

正则表达式语法

例子

匹配下列文本中的 IP 地址

255.255.255.1
255.255.0.1
256.256.255.1
256.256.255
abcd.efg.hig.c
giduihda
19216801
192.16801
192.168.0.1
10.32.14.754
4.2.2.1

正则表达式

\b((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)\b

Python 运行程序

在 Python 正则表达式中,括号是用来捕获组的,只有通过括号捕获的部分才会被 findall 函数返回,所以需要先把括号展开再查找字符串

import re
p = r'\b(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\b'
string = '''
255.255.255.1
255.255.0.1
256.256.255.1
256.256.255
abcd.efg.hig.c
giduihda
19216801
192.16801
192.168.0.1
10.32.14.754
4.2.2.1
'''
print(re.findall(p,string))