简介
正规表达式(Regular Expression,简写为RE),是一个字符串模型,描述了某个句法的规则,可以用来在文本中进行匹配。
正则不是Python语言的产物,最初出现于形式化语言理论中。现在很多语言支持了正则表达式,Python于1.5版本引入了re模块,拥有了全部的正则表达式功能。
re模块使用
方法
re.search()可用于扫描整个字符串并返回第一个成功的匹配。
语法
re.search(pattern, string, flags=0)
pattern 是用于匹配的正则表达式
string 是要进行扫描的字符串
flags 用于控制正则表达式的匹配方式
flags可选项
| 修饰符 | 描述 | 备注 |
|---|---|---|
| re.I | 使匹配对大小写不敏感 | |
| re.S | 使.匹配包括换行在内的所有字符 |
.说明见正则常用语法
|
| re.U | 根据Unicode字符集解析字符 |
语法示例
[Python Console]
>>> import re
>>> str = 'hello world'
>>> pattern = 'hello (.)orld'
>>> match = re.search(pattern, str)
>>> match.group()
'hello world'
>>> match.groups()
('w',)
示例说明
正则表达式语法在下方说明,先说明re模块相关。
re.search()返回一个re.Match类对象,
可以对该对象使用:
-
group()方法获取匹配到的完整字符串 -
groups()方法可以获取匹配到的完整字符串中,匹配规则中占位符所对应的字符串
正则常用语法
总结了一些在此次工程中用到的正则语法。
| 占位符 | 语法 | 示例 |
|---|---|---|
| () | 对正则表达式分组并保存匹配的文本 | 示例1 |
| . | 用于匹配任意单个字符,换行符除外 | 示例1 |
| * | 将前方字符串匹配规则修改为匹配0~多个 | 示例2 |
| + | 将前方字符串匹配规则修改为匹配1~多个 | 与示例2类似 |
| ? | 修饰前方字符串匹配规则,进行最短匹配 (又称非贪婪模式。默认匹配模式为最长匹配, 会匹配目标字符串中最长符合规则的子串) |
示例3 |
| \s | 匹配空白字符(空格,换行符等) | 示例4 |
| [...] | 匹配一组字符,单独列出:[abc]匹配a,b或c
|
|
| [^...] | 匹配不在[]中的字符:[^abc]匹配除了a,b,c之外的字符 |
示例
示例2
[Python Console]
>>> import re
>>> str = 'hello world world'
>>> pattern = 'hello (.*)orld'
>>> match = re.search(pattern, str)
>>> match.group()
'hello world world'
>>> match.groups()
('world wo',)
说明:正则默认进行了最长匹配(又称贪婪匹配),即在有多种符合规则的子串中(hello world和hello world world均符合规则),返回最长的子串。
示例3
[Python Console]
>>> import re
>>> str = 'hello world world'
>>> pattern = 'hello (.*?)orld'
>>> match = re.search(pattern, str)
>>> match.group()
'hello world'
>>> match.groups()
('wo',)
说明:与示例2最长匹配相对,?将匹配规则改为最短匹配(又称非贪婪匹配)
示例4
[Python Console]
>>> import re
>>> str = 'hello world world'
>>> pattern = 'hello(\\s*?)world'
>>> match = re.search(pattern, str)
>>> match.group()
'hello world'
>>> match.groups()
(' ',)
说明:Python字符串中\字符需要转义,\s匹配空格,*修饰匹配多个,?设置为最短匹配
需要转义的字符
这里只总结了此次遇到的一些需要转义的字符(前面加上\)
| * | ( | ) | \ |
|---|













网友评论