Python學習 ——Regex,pythonRegex

來源:互聯網
上載者:User

Python學習 ——Regex,pythonRegex

Regex是一個特殊的字元序列,它能協助你方便的檢查一個字串是否與某種模式比對。

re 模組使 Python 語言擁有全部的Regex功能。

compile 函數根據一個模式字串和可選的標誌參數產生一個Regex對象。該對象擁有一系列方法用於Regex匹配和替換。

re 模組也提供了與這些方法功能完全一致的函數,這些函數使用一個模式字串做為它們的第一個參數

1.Regex修飾符 --可選標誌

   Regex可以包含一些可選標誌修飾符來控制匹配的模式

 修飾符被指定為一個可選的標誌。多個標誌可以通過按位OR(|)來指定。如re.I | re.M 被設定成I 和M 的標誌

  

修飾符 描述
re.I 使匹配對大小寫不敏感
re.L 做本地化識別(locale-aware)匹配
re.M 多行匹配,影響 ^ 和 $
re.S 使 . 匹配包括換行在內的所有字元
re.U 根據Unicode字元集解析字元。這個標誌影響 \w, \W, \b, \B.
re.X 該標誌通過給予你更靈活的格式以便你將Regex寫得更易於理解。

 

2.Regex模式

    列出了Python支援的Regex元字元和文法(圖片來自http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html)

   

3.re模組

   1)re.match函數

  re.match 嘗試從字串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。

  函數文法: re.match(pattern, string, flags=0)

  pattern:匹配的Regex

  string:匹配的字串

  flags:標誌位,用於控制Regex的匹配方式,如:是否區分大小寫,多行匹配等等。

  匹配成功re.match方法返回一個匹配的對象,否則返回None。


start()                 返回匹配開始的位置                                                                                    
end() 返回匹配結束的位置
span() 返回一個元組包含匹配 (開始,結束) 的位置
group() 返回被 RE 匹配的字串
group(num=0) 匹配的整個運算式的字串,group() 可以一次輸入多個組號,在這種情況下它將返回一個包含那些組所對應值的元組。
groups() 返回一個包含所有小組字串的元組,從 1 到 所含的小組號。

 






執行個體一:
 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 ''' 4 # @time    : 2017/4/26 20:03 5 # @author  : huange 6 # @version : 1.1 7 # @file    : test2.py 8 # @Software: PyCharm 9 '''10 import re11 print(re.match('www','www.hh.com').span())     # 在起始位置匹配12 print(re.match('com','www.hh.com'))            # 不在起始位置匹配13 14 15 結果:16 (0,3)17  None
執行個體二:
 1 #!/usr/bin/python3 2 import re 3  4 line = "Cats are smarter than dogs" 5  6 obj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) 7  8 if obj: 9    print ("obj.group() : ", obj.group())10    print ("obj.group(1) : ", obj.group(1))11    print ("obj.group(2) : ", obj.group(2))12    print(obj.start())13    print(obj.end())14    print(obj.groups())15 else:16    print ("No match!!")17 18 19 結果:20 obj.group() :  Cats are smarter than dogs21 obj.group(1) :  Cats22 obj.group(2) :  smarter23 024 2625 ('Cats', 'smarter')
2)re.search函數
re.search掃描整個字串並返回第一個成功的匹配
函數文法: re.match(pattern,string, flags=0)
pattern:匹配的Regex
string:匹配的字串
flags:標誌位,用於控制Regex的匹配方式,如:是否區分大小寫,多行匹配等等。

匹配成功re.search方法返回一個匹配的對象,否則返回None。

執行個體一:
1 import re2 print(re.search('www','www.hh.com').span())3 print(re.search('com','www.hh.com').span())4 5 結果:6      (0,3)7      (7,10)
執行個體二:
 1 #!/usr/bin/python3 2 import re 3  4 line = "Cats are smarter than dogs" 5  6 obj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) 7    8 if obj: 9     print ("obj.group() : ", obj.group())10     print ("obj.group(1) : ", obj.group(1))11     print ("obj.group(2) : ", obj.group(2))12     print(obj.start())13     print(obj.end())14     print(obj.groups())15 else:16     print ("No match!!")17 18  19  結果:20  obj.group() :  Cats are smarter than dogs21  obj.group(1) :  Cats22  obj.group(2) :  smarter23  024  2625 ('Cats', 'smarter')
PS:re.match只匹配字串的開始,如果字串開始不符合Regex,則匹配失敗,函數返回None; re.search匹配整個字串,直到找到一個匹配。

3)re.sub函數
  re.sub用於替換字串中匹配到的選項
  函數文法:re.sub(pattern, repl, string, count=0)
 
pattern : 正則中的模式字串。
  repl : 替換的字串,也可為一個函數。
  string : 要被尋找替換的原始字串。
  count : 模式比對後替換的最大次數,預設 0 表示替換所有的匹配。

執行個體一:
 1 #!/usr/bin/python3 2 import re 3 phone = '135-4238-5642  # 電話號碼' 4  5 # 刪除注釋 6 num = re.sub('#.*$','',phone) 7 print(num) 8  9 # 刪除非字元10 num = re.sub('\D','',phone)11 print(num)12 13 結果:14     135-4238-5642  15     13542385642

  執行個體二:

 1 #!/usr/bin/python 2  3 import re 4  5 # 將匹配的數字乘於 2 6 def double(matched): 7     value = int(matched.group('value')) 8     return str(value * 2) 9 10 s = 'A23G4HFD567'11 print(re.sub('(?P<value>\d+)', double, s))12 13 結果為: 14      A46G8HFD1134

4)re.split函數

   函數文法:re.split(pattern,string,maxsplit)
 按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。

 

1 import re2 3 p = re.split(r'\d+','one1two2three3four4')4 print(p)

結果:
['one','two','three','four','']

5)re.findall函數
   以列表的形式返回能全部匹配到的子串

 函數文法:re.findall(pattern, string ,flags):

  

1 import re2 3 p = re.findall(r'\d+','one1two2three3four4')4 print(p)5 6 結果:7         ['1','2','3','4']


 


 


 


 

 

 










聯繫我們

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