体验 python re module

2011-10-09  李琪 

#-*- coding:utf-8 -*-
'''
Created on 2011-10-9
作者: 李昱彤
Email: liqi1031@gmail.com
'''

import re

print '------------------example1---------------------'
m = re.match('^[f-z]+', 'fool dfool')
#匹配成功,就返回匹配对象,匹配对象才有group() and groups() 方法
print m
if m <> None:
    print m.group()

print '-------------example2----------------'
m = re.match('foo', 'goo')
#匹配失败,就返回None
print m

pattern = '^\-?[0-9]*.[0-9]+$'
#? 表示重复0次或一次
#× 表示重复0次或多次
#+ 表示重复1次或多次
string = '-10000.250'
m = re.match(pattern, string)
print '------------------example3--------------------'
print m
if m <> None:
    print m.group()
   

#search() 查找模式
m = re.search('foo', 'dfool sb. out of sth. fool sb. out of sth.')
print '-----------------example4---------------------'
if m <> None:
    print m.group()
   
#匹配多个字符串|
print '-----------------------example5------------------------'
pattern ='bat|bet|bit|but'
m = re.match(pattern, 'bat', flags=0)
if m <> None:
    print m.group()
   
m = re.match(pattern, "It's not u but me!")
if m <> None:
    print m.group()

m = re.search(pattern, "It's not u but me!", flags=0)
if m <> None:
    print m.group()
   
#匹配任意一个单字符.
print '----------------------example6------------------------'
pattern = '.one'
m = re.match(pattern, "bone", flags=0)
if m <> None:
    print m.group()
   
m = re.match(pattern, "one", flags=0)
if m <> None:
    print m.group()

m = re.match(pattern, " none", flags=0)
if m <> None:
    print m.group()
   
m = re.search(pattern, "The one")
if m <> None:
    print m.group()
   
pattern = "3\.14"
m = re.match(pattern, '3.14', flags=0)
if m <> None:
    print m.group()

pattern = "3.14"
m = re.match(pattern, "3014")
if m <> None:
    print m.group()

#字符集[]
print '------------------example7---------------------'
pattern = '[cr][23][dp][o2]'
m = re.match(pattern, "c3po")
if m <> None:
    print m.group()

#正则表达式的分组
print '------------------example8----------------------'

运行结果:

------------------example1---------------------
<_sre.SRE_Match object at 0x01636D08>
fool
-------------example2----------------
None
------------------example3--------------------
<_sre.SRE_Match object at 0x01636D08>
-10000.250
-----------------example4---------------------
foo
-----------------------example5------------------------
bat
but
----------------------example6------------------------
bone
 one
3.14
3014
------------------example7---------------------
c3po
------------------example8----------------------

384°/3835 人阅读/1 条评论 发表评论

赵云峰  2011-10-10

顶一个。。。


登录 后发表评论