Python模組學習 re Regex

來源:互聯網
上載者:User

re.match
  re.match 嘗試從字串的開始匹配一個模式,如:下面的例子匹配第一個單詞。 複製代碼 代碼如下:import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.match(r"(\w+)\s", text)
if m:
print m.group(0), '\n', m.group(1)
else:
print 'not match'

re.match的函數原型為:re.match(pattern, string, flags)
第一個參數是Regex,這裡為"(\w+)\s",如果匹配成功,則返回一個Match,否則返回一個None;
第二個參數表示要匹配的字串;
第三個參數是標緻位,用於控制Regex的匹配方式,如:是否區分大小寫,多行匹配等等。
re.search
  re.search函數會在字串內尋找模式比對,只到找到第一個匹配然後返回,如果字串沒有匹配,則返回None。 複製代碼 代碼如下:import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.search(r'\shan(ds)ome\s', text)
if m:
print m.group(0), m.group(1)
else:
print 'not search'

re.search的函數原型為: re.search(pattern, string, flags)
每個參數的含意與re.match一樣。
re.match與re.search的區別:re.match只匹配字串的開始,如果字串開始不符合Regex,則匹配失敗,函數返回None;而re.search匹配整個字串,直到找到一個匹配。
re.sub
  re.sub用於替換字串中的匹配項。下面一個例子將字串中的空格 ' ' 替換成 '-' : 複製代碼 代碼如下:import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s+', '-', text)

re.sub的函數原型為:re.sub(pattern, repl, string, count)
其中第二個函數是替換後的字串;本例中為'-'
第四個參數指替換個數。預設為0,表示每個匹配項都替換。
re.sub還允許使用函數對匹配項的替換進行複雜的處理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);將字串中的空格' '替換為'[ ]'。
re.split
  可以使用re.split來分割字串,如:re.split(r'\s+', text);將字串按空格分割成一個單字清單。
re.findall
  re.findall可以擷取字串中所有匹配的字串。如:re.findall(r'\w*oo\w*', text);擷取字串中,包含'oo'的所有單詞。
re.compile
  可以把Regex編譯成一個Regex對象。可以把那些經常使用的Regex編譯成Regex對象,這樣可以提高一定的效率。下面是一個Regex對象的一個例子: 複製代碼 代碼如下:import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
regex = re.compile(r'\w*oo\w*')
print regex.findall(text) #尋找所有包含'oo'的單詞
print regex.sub(lambda m: '[' + m.group(0) + ']', text) #將字串中含有'oo'的單詞用[]括起來。

更詳細的內容,可以參考Python手冊。

相關文章

聯繫我們

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