python正则表达式的简单使用

本文介绍Python中正则表达式的使用方法,包括模块函数`re.compile()`, `re.match()`, `re.search()`, `re.split()`和`re.sub()`的功能与用法,并通过实例演示了如何在字符串操作中灵活运用这些函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块函数

re.compile(pattern [, flag])

把正则表达式预编译成正则表达式对象(模式对象),供以后使用.

#模式对象,有re.compile()返回
>>> pobj = re.compile('Hello,(.*)')
>>> pobj
<_sre.SRE_Pattern object at 0x7fb83dc9a530>

re.match(pattern, string [, flag])

如果字符串起始处有0个或多个字符串匹配模式字符串, 返回一个相应的匹配对象.否则返回None.等同于re.search的^pattern.

>>> re.match('Hello,(.*)', 'Hello, you are welcome!')
<_sre.SRE_Match object at 0x7fb83db596c0>

re.search(pattern, string [, flag])

扫描字符串string, 返回匹配pattern模式的匹配对象(mobj),否则返回None.

>>> re.search('(you are)', 'Hello, you are welcome!')
<_sre.SRE_Match object at 0x7fb83db59648>

re.split(pattern, string [, maxsplit=0])

用指定模式分解字符,返回分解后的列表.

>>> re.split('--', 'spam--egg--bar')
['spam', 'egg', 'bar']

re.sub(pattern, repl, string, count=0, flags=0)

pattern模式替换string后的字符串由repl返回, repl可以是函数或者字符串.

>>> print re.sub(r'(.*)--(.*)--(.*)', r'I like \1 and \2, not \3', 'spam--egg--bar') 
I like spam and egg, not bar

正则表达式对象(模式对象)

模式对象是由re.compile()返回的对象, 拥有与re模块同构的函数. 如pobj.match(string [, flag]), pobj.search(string [, flag])等

匹配对象的方法

mobj.group(n)

返回n指定的匹配对象.

mobj.groups()

返回所有的匹配对象, 用元组表示.

简单实例

#coding=utf-8
import re

string = 'Hello, you are welcome!'

#预编译成模式对象,由re.compile()返回
pobj = re.compile('Hello,(.*)')

#匹配对象,由match()返回mobj
mobj = pobj.match(string)
print mobj.group(1) #调用匹配对象的方法group()

#可以不生成模式对象, 直接调用re模块函数, 简写为
print re.match('Hello,(.*)', 'Hello, you are welcome!').group(1)
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值