pyRegex

來源:互聯網
上載者:User

# -*- 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']

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.