Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Python 正则表达式

$
0
0

本篇文章将以例子的形式讲解Python语言正则表达式的使用。分为两大部分:函数部分和正则书写部分。我们所使用的模块是re模块。

1 正则表达式中常用函数

1.1 测试group()函数

def testGroup():
    #对正则表达式进行编译,获得编译后的对象
    pattern = re.compile('flankwang')
    #用编译后的正则表达式对目标字符串进行切分
    match = pattern.match('flankwang@peirong')
    #测试group函数
    if match :
        print 'match.group(0):',match.group(0),' match.group():',match.group()

结果:

match.group(0): flankwang  match.group(): flankwang

总结:使用正则需要先引入正则模块re;然后对正则表达式进行编译;然后根据编译获得的对象对目标字符串进行切割;然后拿到匹配到的对象。re.compile方法用来编译正则表达式;match方法用来对目标字符串进行切割;group函数把匹配上的对象拿出来。

1.2 测试group()函数和groups()函数

def testGroupAndGroups():
    #对正则表达式进行编译,获得编译后的对象
    pattern = re.compile('(flankwang)@(peirong)')
    #用编译后的正则表达式对目标字符串进行切分
    match = pattern.match('flankwang@peirong')
    #测试group函数
    if match :
        print 'match.group(0):',match.group(0),' match.group(1):',match.group(1),'match.group(2):',match.group(2)
    #测试groups函数
    if match :
        print 'match.groups():',match.groups(),' match.groups()[0]:',match.groups()[0]

结果:

match.group(0): flankwang@peirong  match.group(1): flankwang match.group(2): peirong
match.groups(): ('flankwang', 'peirong')  match.groups()[0]: flankwang

总结:先看正则表达式(flankwang)@(peirong),每个括号为一个子组,groups()函数返回一个元组,内容第一个对应第一个子组,内容第二个对应第二个子组。

作者:lovemelovemycode 发表于2013-1-24 15:19:47 原文链接
阅读:41 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>