在python中使用Regex(二)

來源:互聯網
上載者:User

標籤:樣本   color   字串   img   lag   Regex   字元   recent   image   

 

這一節主要學習一下compile()函數和group()方法
1.  re.compile()

compile 函數用於編譯Regex,產生一個Regex( Pattern )對象,然後就可以用編譯後的Regex去匹配字串

文法如下:
>>> help(re.compile)Help on function compile in module re:compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object.
>>>
pattern : 一個字串形式的Regex
flags :可選,表示匹配模式,比如忽略大小寫,多行模式等

樣本:

>>> test_pattern = re.compile(r‘\d{2}‘)   # 編譯一個Regex,並將其賦給一個變數>>> m = test_pattern.match(‘12bc34‘)   # 使用編譯後的Regex對象直接匹配字串>>> m<_sre.SRE_Match object; span=(0, 2), match=‘12‘>
>>> test_pattern = re.compile(r‘a\w+‘)  # 產生一個Regex對象(這裡是匹配以a開頭的單詞)>>> m = test_pattern.findall(‘apple,blue,alone,shot,attack‘) # 使用findall()函數匹配所有滿足匹配規則的子串>>> m[‘apple‘, ‘alone‘, ‘attack‘]
2.group()和groups()

一般用match()或search()函數匹配,得到匹配對象後,需要用group()方法獲得匹配內容;同時也可以提取分組截獲的字串(Regex中()用來分組)

樣本:

>>> pattern = re.compile(r‘^(\d{3})-(\d{3,8})$‘)  # 匹配一個3位元開頭,然後一個-,然後跟著3-8位元字的字串>>> m = pattern.match(‘020-1234567‘)>>> m<_sre.SRE_Match object; span=(0, 11), match=‘020-1234567‘>>>> m.group()   #  顯示整個匹配到的字元‘020-1234567‘>>> m.group(0)  # 同樣是顯示整個匹配到的字元‘020-1234567‘  >>> m.group(1)   # 提取第1個分組中的子串‘020‘>>> m.group(2)   # 提取第2個分組中的子串‘1234567‘>>> m.group(3)   # 因為不存在第3個分組,所以這裡會報錯:沒有這樣的分組Traceback (most recent call last):  File "<pyshell#73>", line 1, in <module>    m.group(3)IndexError: no such group

>>> m.groups()
(‘020‘, ‘1234567‘)
>>>


2018-06-07 22:43:46

 

在python中使用Regex(二)

聯繫我們

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