py正则表达式

来源:互联网 发布:淘宝店女装推荐 编辑:程序博客网 时间:2024/04/28 21:36

# -*- coding: utf-8 -*-
"""
添加中文注释 要加上开头的# -*- coding: utf-8 -*-
或者 # -*- coding: cp936 -*-   不然报错
"""
import re


"""
正则表达式查找邮件
"""
part = '/w+@(/w+/.)?/w+/.com'
print re.match(part, 'nobady@xxx.com').group()
print re.match(part, 'tangxiao@163henghaoji.com').group()

"""
groups()和group()的使用   前者返回一个元祖,后者返回一个对象
"""
str = '12ta-123'
m = re.match('(/w/w/w/w)-(/d/d/d)', str)
print m.group()   #12ta-123

print m.group(1)#12ta

print m.group(2)#123

print m.groups() #('12ta', '123')


"""
用findall()找到每个出现的匹配部分  它返回一个列表
"""
print re.findall('car', 'car')  #['car']
print re.findall('car', 'tangcar is a goodcar car is mycar')#['car', 'car', 'car', 'car']

"""
用sub()[和 subn()]进行搜索和替换
sub()和subn(). 二者几乎是一样的,都是将某
字符串中所有匹配正则表达式模式的部分进行替换。用来替换的部分通常是
一个字符串,但也可能是一个函数,该函数返回一个用来替换的字符串。
subn()和sub()一样,但它还返回一个表示替换次
数的数字,替换后的字符串和表示替换次数的数字作为一个元组的元素返
sub(要找的模式, 替换的字符, 被查找的字符串)
"""

print re.sub('X', 'tang', 'X is a good student') #tang is a good student
print re.subn('X', 'tang', 'X is a good student') #('tang is a good student', 1)


"""
用split()分割(分隔模式)
"""

stringss = 'tang hu nan come on'
print re.split(' ', stringss) #['tang', 'hu', 'nan', 'come', 'on']
print re.split(' ', stringss, 3)#['tang', 'hu', 'nan', 'come on']

原创粉丝点击