python中Regex的應用講解

來源:互聯網
上載者:User
這篇文章主要介紹了pythonRegex的使用,需要的朋友可以參考下

python的正則是通過re模組的支援

匹配的3個函數

match :只從字串的開始與Regex匹配,匹配成功返回matchobject,否則返回none;

re.match(pattern, string, flags=0) ##flags標誌位,用於控制Regex的匹配方式,如:是否區分大小寫,多行匹配等等。

search :將字串的所有字串嘗試與Regex匹配,如果所有的字串都沒有匹配成功,返回none,否則返回matchobject;(re.search相當於perl中的預設行為)

findall方法,返回所有的與給定的運算式匹配的一個list;

使用


mypatten = re.compile("規則") ##定義匹配的規則myresult = mypatten.match("字串") ##匹配結果

if myresult:

  print myresult.group()##括弧中可以填數字也可以 命名分組 (?P<name>Regex)#name是一個合法的標識符

search於match一樣


mypatten = re.compile("規則") ##定義匹配的規則myresult = mypatten.findall("字串") ##返回的是個列表 如果裡面有分組返回的是個二維列表

if myresult: 


print myresult.group()

聯繫我們

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