# -*- coding: utf-8 -*-
"""
添加中文注釋 要加上開頭的# -*- coding: utf-8 -*-
或者 # -*- coding: cp936 -*- 不然報錯
"""
import re
"""
Regex尋找郵件
"""
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(). 二者幾乎是一樣的,都是將某
字串中所有匹配Regex模式的部分進行替換。用來替換的部分通常是
一個字串,但也可能是一個函數,該函數返回一個用來替換的字串。
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']