(學習)python非貪婪、多行匹配Regex例子

來源:互聯網
上載者:User

一些regular的tips:

1 非貪婪flag >>> re . findall ( r " a( \d +?) " , " a23b " ) # 非貪婪模式
         [ ' 2 ' ]
>>> re . findall ( r " a( \d +) " , " a23b " )
         [ ' 23 ' ]

注意比較這種情況: >>> re . findall ( r " a( \d +)b " , " a23b " )
         [ ' 23 ' ]
>>> re . findall ( r " a( \d +?)b " , " a23b " ) #如果前後均有限定條件,則非匹配模式失效
         [ ' 23 ' ]

2 如果你要多行匹配,那麼加上re.S和re.M標誌
re.S:.將會匹配分行符號,預設.逗號不會匹配分行符號 >>> re . findall ( r " a( \d +)b.+a( \d +)b " , " a23b \n a34b " )
         []
>>> re . findall ( r " a( \d +)b.+a( \d +)b " , " a23b \n a34b " , re . S )
         [( ' 23 ' , ' 34 ' )]
>>>

re.M:^$標誌將會匹配每一行,預設^只會匹配符合正則的第一行;預設$只會匹配符合正則的末行 >>> re . findall ( r " ^a( \d +)b " , " a23b \n a34b " )
         [ ' 23 ' ]
>>> re . findall ( r " ^a( \d +)b " , " a23b \n a34b " , re . M )
         [ ' 23 ' , ' 34 ' ]

但是,如果沒有^標誌, >>> re . findall ( r " a( \d +)b " , " a23b \n a34b " )
         [ ' 23 ' , ' 43 ' ]

可見,是無需re.M


import re

n='''12 drummers drumming,
11 pipers piping, 10 lords a-leaping'''

p=re.compile('^\d+')
p_multi=re.compile('^\d+',re.MULTILINE) #設定 MULTILINE 標誌
print re.findall(p,n)  #['12']
print re.findall(p_multi,n) # ['12', '11']

============================

import re
a = 'a23b'
print re.findall('a(\d+?)',a)  #['2']
print re.findall('a(\d+)',a) #['23']
print re.findall(r'a(\d+)b',a) #['23']
print re.findall(r'a(\d+?)b',a) # ['23']
============================
b='a23b\na34b'
''' . 匹配非分行符號的任意一個字元'''

print re.findall(r'a(\d+)b.+a(\d+)b',b) #[]

print re.findall(r'a(\d+)b',b,re.M) # ['23', '34']

print re.findall(r'^a(\d+)b',b,re.M) # ['23', '34']

print re.findall(r'a(\d+)b',b) #['23','34'] 可以匹配多行

print re.findall(r'^a(\d+)b',b) # ['23'] 預設^只會匹配符合正則的第一行

print re.findall(r'a(\d+)b$',b) # ['34'] 預設$只會匹配符合正則的末行

print re.findall(r'a(\d+)b',b,re.M) #['23', '34']

print re.findall(r'a(\d+)b.?',b,re.M)  # ['23', '34']

print re.findall(r"a(\d+)b", "a23b\na34b")  # ['23', '34']

============================

聯繫我們

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