python學習之Regex筆記,pythonRegex

來源:互聯網
上載者:User

python學習之Regex筆記,pythonRegex

最近在學習《集體編程智慧》的第三章節,裡面在對資料的提取中使用了Regex,網上的解說有很多,但是感覺不具體,有些術語,給人一種不明覺厲的感覺,而且文章的例子太少,多是文字和表格解說型的,不好理解 ,於是在自己學習了相關內容後,用自己的話語來寫一篇關於Regex的文章,多多指教:

什麼是Regex:
Regex(或者RE)是一種小型的、高度專業化的程式設計語言,它內嵌於python 中,並能過re模組來實現對它的操作。在以下幾種情況下會使用到Regex:
*1.字串匹配
2.指定字串替換
3.指定字串尋找,例如尋找英文語句,e-mail地址、命令等
4.字串分割*

先上幾道涼菜,不過,沒耐心或者有基礎的也可以直接進入正餐~
1.re的簡介
使用python的re模組,儘管不能滿足所有複雜的匹配情況,但足夠在絕大多數情況下能夠有效地實現對複雜字串的分析並提取出相關資訊。

2.re的Regex文法

Regex文法表如下:

文章讀到此處,你可能就有點沒耐心了,好菜才開始上桌,客官你請慢慢品嘗。
在python中使用Regex,我們需要先自己定義一個正則式,然後把你的正則式與你需要的字串進行匹配,實現你想要的功能,那怎樣去定義這個正則式呢,我們先看一個例子

import res = r'abc'                                #正則式print re.findall(s, "aaaa")               #在目標字串 "aaaa"匹配正則式print re.findall(s, "abcaaaaaaa")

output
[]
[‘abc’]

看到這裡,你是不是想問,為什麼正則式中會出現個’r’,原因是有各種各樣的字元,當它們在Regex中使用,將有特殊的意義。為了避免在處理Regex的任何困惑,將使用原始字串作為r’expression(expression為未經處理資料,作為匹配項)“,即,無論裡面有沒有像’\’, ‘+’這種特殊字元,都按未經處理資料來匹配,不用考慮其特殊含義。

Regex中的常用的元字元有下幾種,它們使得匹配規則更加靈活

. ^   $  *  +  ?  {}  []  \  |  ()
inputimport rest = "top tip tqp twp tep"res = r't[io]p' #尋找top,tip,即匹配 []裡面的一個字元print re.findall(res, st)

output:

[‘top’, ‘tip’]

import rer = r"[0-9]"print re.findall(r, '1234567')

output

[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’]

需要注意的是:元字元在字元集[]裡面不起作用,請看下面這個例子:

st = "top tip tqp twp tep"res = r't[^io]p'           #^的作用是匹配除了tip與 top的單詞print re.findall(res, st)

output

[‘tqp’, ‘twp’, ‘tep’]

import res = "hello world, hello boy"r = r"^hello"g = r"boy$"print re.findall(r, s)print re.findall(g, s)

output

[‘hello’]
[‘boy’]

3.\
a.反斜線的後面添加不同的字元以表示不同的特殊意義
b.也可以用於取消所有的元字元:[或\
Regex特殊序列表如下:

import rer = r'\d'print re.findall(r, "1254a2")

output

[‘1’, ‘2’, ‘5’, ‘4’, ‘2’]

各位看官等等,現在讓我們來寫一個python小程式來匹配電話號碼,假如北京的的號碼格式如下所示:
010-12345678
按照前面所述的內容,寫一個程式

import rer = r"^010-\d\d\d\d\d\d\d\d"print re.findall(r, "010-12345678")

output

[‘010-12345678’]

但是反覆輸入8個%d挺麻煩的,假如資料有100個,那手都會殘掉,還容易漏掉,Regex中有一類元字元就是來解決這種重複問題的,上面這個號碼匹配的程式可以改成如下

import rer = r"^010-\d{8}"print re.findall(r, "010-12345678")

output

[‘010-12345678’]

可用於重複的字元
指定字元可匹配零次或者多次(不超過匹配界定範圍,20億次)

import rer = r"ab*"print re.findall(r, "a")print re.findall(r, "ab")print re.findall(r, "abbbbbb")

output

[‘a’]
[‘ab’]
[‘abbbbbb’]

2.+
表示匹配一次或者多次

import rer = r"ab+"print re.findall(r, "a")print re.findall(r, "ab")print re.findall(r, "abbbbbb")

output

[]
[‘ab’]
[‘abbbbbb’]

總結:‘+’ 與’*’的區別就在於+至少需要重複一次
3.?
匹配一次或者零次,可以認為它用於標識某事物是可選的
4{m, n}
m,n為整數,它表示至少重複m次,最多重複n次

import rer = r"a{1,3}"print re.findall(r, 'a')print re.findall(r, 'aa')print re.findall(r, 'aaaa')

output
[‘a’]
[‘aa’]
[‘aaa’, ‘a’]

那麼在python中是怎樣使用Regex的呢?
pythonre內的re模組提供了一個Regex引擎的介面,可以讓我們將REstring編譯成對象並用它們來進行匹配
3.re的主要功能函數
常用的功能函數包括:compile、search、match、split、findall(finditer)、sub(subn)
(1)compile
re.compile(pattern[, flags])
作用:把Regex文法轉化成Regex對象,我們常常會使用到compile函數定義成一個Regex對象再進行匹配,為什麼要使用compile函數,而不用前面我們程式中直接定義正則式的形式呢?原因是:如果我們高頻用到正則式去匹配時,使用 compile 函數把它變成Regex對象,可以提高匹配速度。
flags定義包括:
re.I:忽略大小寫
re.L:表示特殊字元集 \w, \W, \b, \B, \s, \S 依賴於當前環境
re.M:多行模式
re.S:’ . ‘並且包括分行符號在內的任一字元(注意:’ . ‘不包括分行符號)
re.U: 表示特殊字元集 \w, \W, \b, \B, \d, \D, \s, \S 依賴於 Unicode 字元屬性資料庫

為什麼需要使用選項標誌符呢,先看看下面的例子:

import revsvt_re = re.compile(r'vsvt', re.I)        #執行不區分大小寫匹配。print vsvt_re.findall('vSVT')

output
重點內容[‘vSVT’]

(2)search
re.search(pattern, string[, flags])
search (string[, pos[, endpos]])
作用:在字串中尋找匹配Regex模式的位置,返回 MatchObject 的執行個體,如果沒有找到匹配的位置,則返回 None。

(3)match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函數只在字串的開始位置嘗試匹配Regex,也就是只報告從位置 0 開始的匹配情況,而 search() 函數是掃描整個字串來尋找匹配。如果想要搜尋整個字串來尋找匹配,應當用 search()。

下面三個小例子可以看出mathc()與 search()的區別

import revsvt_re = re.compile(r'vsvt')print vsvt_re.match('vsvt hello').group()   #因為match 返回的是一個對象,要想看到成員,就需要調用group()

output
vsvt

import revsvt_re = re.compile(r'vsvt')print vsvt_re.match('hello vsvt ')

output
None

import revsvt_re = re.compile(r'vsvt')print vsvt_re.search('hello vsvt ').group()

**重點內容**output
vsvt

(4)finditer()
找到RE匹配的所有子串,並把它們作為一個迭代器返回

import revsvt_re = re.compile(r'vsvt')x = vsvt_re.finditer("vsvt hello vsvt and vsvt")print x.next().group()

output
vsvt

(5)sub()
函數功能:用來替換字串
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it’s passed the match object and must return
a replacement string to be used.
pattern為Regex,repl 是被替換的對象, string被替換的字串

import rers = r'c..t'print re.sub(rs, "python", "caat cact kite hello")

output
python python kite hello

(6)split()
函數功能:用來拆分字串

import reoper_re = re.compile(r'[\+\-\*]')print re.split(oper_re, "123 + 23-34 * 2")

output
[‘123 ‘, ’ 23’, ‘34 ‘, ’ 2’]

我們在學習相關模組的時候,如果想看看該模組或者函數的功能,我們可以使用以下兩條指令
dir(re) #協助我們查看re 模組的內建屬性和方法
help(re.sub) #協助我們查看函數功能

相關文章和視頻連結:
http://www.jb51.net/article/34642.htm
http://www.crifan.com/python_re_sub_detailed_introduction/
http://www.169it.com/article/9913111281939258943.html
http://www.icoolxue.com/play/1943(vedio)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.