python3 re结合正则表达式怎么用

发布时间:2020-11-21 09:30:11 作者:小新
来源:亿速云 阅读:157

小编给大家分享一下python3 re结合正则表达式怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

# 推荐使用 Python 正则表达式的几个步骤
import re
regex = re.compile(r'正则表达式') # 创建一个 Regex 对象,使用 r'' 原始字符串不需要转义
regex.match() #
regex.search() # 返回一个 Match 对象,包含被查找字符串中的第一次被匹配的文本
regex.findall() # 返回一组字符串列表,包含被查找字符串中的所有匹配
regex.sub()  # 替换字符串,接收两个参数,新字符串和正则表达式
...

简单示例:

>>> import re
>>> regex = re.compile(r'\b\w{6}\b') # 匹配6个字符的单词
>>> regex.search('My phone number is 421-2343-121')
>>> text = regex.search('My phone number is 421-2343-121')
>>> text.group()      # 调用 group() 返回结果
'number'
 
>>> regex = re.compile(r'0\d{2}-\d{8}|0\d{3}-\d{7}') # 注意分枝条件的使用
>>> text = regex.search('My phone number is 021-76483929')
>>> text.group()
'021-76483929'
>>> text = regex.search('My phone number is 0132-2384753')
>>> text.group()
'0132-2384753'
 
>>> regex = re.compile(r'(0\d{2})-(\d{8})') # 括号分组的使用
>>> text = regex.search('My phone number is 032-23847533')
>>> text.group(0)
'032-23847533'
>>> text.group(1)
'032'
>>> text.group(2)
'23847533'
 
>>> regex = re.compile(r'(0\d{2}-)?(\d{8})') # ?之前的分组表示是可选的分组,如果需要匹配真正的?,就使用转义字符\?
>>> text = regex.search('My phone number is 032-23847533')
>>> text.group()
'032-23847533'
>>> text = regex.search('My phone number is 23847533')
>>> text.group()
'23847533'
 
>>> regex = re.compile(r'(Py){3,5}') # Python 默认是贪心,尽可能匹配最长的字符串
>>> text = regex.search('PyPyPyPyPy')
>>> text.group()
'PyPyPyPyPy'
>>> regex = re.compile(r'(Py){3,5}?') # ? 声明非贪心,尽可能匹配最短的字符串
>>> text = regex.search('PyPyPyPyPy')
>>> text.group()
'PyPyPy'

其它正则规则可自行测试。下面是 Python 正则表达式的常用方法:

# 这里测试 findall() 以及 sub()
# findall()
>>> regex = re.compile(r'0\d{2}-\d{8}|0\d{3}-\d{7}')                       
>>> regex.findall('Cell: 021-38294729, Work: 0413-3243243')
['021-38294729', '0413-3243243']
 
>>> regex = re.compile(r'Hello \w+')
>>> regex.sub('Hello Python', 'falkdjfsk Hello c sldfjlksdj Hello java sdfsj')
'falkdjfsk Hello Python sldfjlksdj Hello Python sdfsj'

以上是python3 re结合正则表达式怎么用的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Python3快速入门(七)Python3正则表达式
  2. Python3网络爬虫实战-26、正则表达式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python python3 re 正则表达式

上一篇:python Django怎么实现自定义函数

下一篇:怎么用res函数解决python爬虫的中文乱码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》