什麼是python re.match函數?(執行個體解析)

來源:互聯網
上載者:User
在這篇文章之中我們來瞭解一下關於python之中的Regex,有些朋友可能是剛剛接觸到python這一程式設計語言,對於這一方面不是特別的瞭解,在接下來的文章之中我們來瞭解一下 python中re.match函數, python re.match函數是Python中常用的Regex處理函數。廢話不多說,我們開始進入文章吧。

re.match函數

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

函數的文法

re.match(pattern, string, flags=0)

函數參數說明:

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

我們可以使用group(num) 或 groups() 匹配對象函數來擷取匹配運算式。

執行個體如下:

#!/usr/bin/python# -*- coding: UTF-8 -*-  import reprint(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配

輸出如下:

(0, 3)None
 # !/usr/bin/pythonimport reline = "Cats are smarter than dogs"matchObj = re.match(r'(.*) are (.*?) .*', line, re.M | re.I)if matchObj:    print "matchObj.group() : ", matchObj.group()    print "matchObj.group(1) : ", matchObj.group(1)    print "matchObj.group(2) : ", matchObj.group(2)else:    print "No match!!"

以上執行個體輸出如下:

matchObj.group() :  Cats are smarter than dogsmatchObj.group(1) :  CatsmatchObj.group(2) :  smarter

聯繫我們

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