python 正则表达式 re模块


#1寻常方式python匹配字符串
In [1]: str1='imooc python'
In [2]: str1.find('i')
Out[2]: 0
In [4]: str1.find('z')
Out[4]: -1
In [6]: str1.startswith('i')
Out[6]: True
#2.正则表达式re的使用
import re
#匹配'imooc',re的compile方法生成一个pattern对象
pa=re.compile(r'imooc')
#调用pattern的方法match匹配字符串
#匹配的结果放在math的对象里面,用match的方法显示匹配的结果
ma=pa.match(str1)#返回math对象
ma.group()#匹配字符串的数据
ma.span()#匹配的数据区间
ma.groups()#匹配的元组


In [11]: pa=re.compile(r'Imooc python',re.I)
In [12]: pa
Out[12]: re.compile(r'Imooc python', re.IGNORECASE)#忽略大小写




In [22]: pa=re.compile(r'(imooc)',re.I)

In [23]: ma=pa.match(str1)

In [24]: print ma.groups()#返回一个元组
('imooc',)


In [30]: ma1=re.match(r'imooc','imooc python')#简便写法

In [31]: ma1.group()
Out[31]: 'imooc'

In [32]: ma1=re.match(r'imooc','Z')

In [33]: ma1.group()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-a04cfb428c99> in <module>()
----> 1 ma1.group()

AttributeError: 'NoneType' object has no attribute 'group'

In [34]:











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解Python正则表达式re模块。re模块Python的标准库之一,用于处理正则表达式正则表达式是一种用于匹配和搜索文本的模式,它可以用来检查字符串是否符合特定的格式,或者从字符串中提取想要的信息。 re模块提供了一系列函数和方法来操作正则表达式,包括: - re.compile(pattern, flags):编译正则表达式,返回一个正则表达式对象。 - re.search(pattern, string, flags):在字符串中搜索匹配正则表达式的第一个位置,返回一个匹配对象。 - re.match(pattern, string, flags):从字符串开头开始匹配正则表达式,返回一个匹配对象。 - re.findall(pattern, string, flags):返回字符串中所有匹配正则表达式的子串列表。 - re.sub(pattern, repl, string, count=0, flags=0):用指定的替换字符串替换字符串中所有匹配正则表达式的子串,返回替换后的字符串。 其中,pattern参数是正则表达式,string参数是要匹配的字符串,flags参数是可选的标志,用来控制正则表达式的行为。 例如,下面的代码展示了如何使用re模块来匹配一个简单的正则表达式: ```python import re text = 'Hello, World!' pattern = r'Hello' match = re.search(pattern, text) if match: print('Match found:', match.group()) else: print('No match') ``` 输出结果为: ``` Match found: Hello ``` 以上就是Python正则表达式re模块的基本介绍,希望能帮到您。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值