1. 程式人生 > >Python 正則表示式:compile,match

Python 正則表示式:compile,match

本文以匹配×××ID為例,介紹re模組的compile與match的用法

複雜匹配 = re.compile(正則表示式): 將正則表示式例項化 

            + 

       re.match(要匹配的字串): 從字串開 頭/尾 開始匹配


簡單匹配 = re.match(正則表示式,要匹配的字串): 從字串開 頭/尾 開始匹配


懶癌,配上模組函式解釋好消化

re.match(pattern, string, flags)
第一個引數是正則表示式,如果匹配成功,則返回一個Match,否則返回一個None;
第二個引數表示要匹配的字串;
第三個引數是標緻位,用於控制正則表示式的匹配方式,如:是否區分大小寫,多行匹配等等。
需要特別注意的是,這個方法並不是完全匹配。它僅僅決定在字串開始的位置是否匹配。所以當pattern結束時若還有剩餘字元,仍然視為成功。想要完全匹配,可以在表示式末尾加上邊界匹配符'$'
例如: match(‘p’,’python’)返回值為真;
      match(‘p’,’www.python.org’)返回值為假
--------------------- 
作者:24k千足金閃閃大寶貝貓的小熊 
來源:CSDN 
原文:https://blog.csdn.net/piglite/article/details/81121323 
版權宣告:本文為博主原創文章,轉載請附上博文連結!


方法一:

re.compile(正則表示式).match(要比配的字串)

#!/usr/bin/python
#! -*- coding:utf-8 -*-

import re;

id_num = '440211199606030022'
id_pat = '(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'
id_str = re.compile(id_pat).match(id_num)
print("Match: " + str(id_str.group()))

執行結果:

Match: 440211199606030022


方法二:

物件名1 = re.compile(正則表示式)

物件名2 = 物件名1.match(要比配的字串)

#!/usr/bin/python
#! -*- coding:utf-8 -*-

import re;

id_num = '440211199606030022'
id_pat = '(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'
id_instantiation = re.compile(id_pat)
id_str = id_instantiation.match(id_num)
print("Match: " + str(id_str.group()))

執行結果:

Match: 440211199606030022



方法三:

物件名1 = re.compile(正則表示式)

物件名2 = re.match(物件名1, 要比配的字串)

#!/usr/bin/python
#! -*- coding:utf-8 -*-

import re;

id_num = '440211199606030022'
id_pat = '(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'
id_instantiation = re.compile(id_pat)
id_str = re.match(id_instantiation,id_num)
print("Match: " + str(id_str.group()))


執行結果:

Match: 440211199606030022



方法四:

物件名1 = 正則表示式

物件名2 = re.compile(物件名1, 要比配的字串)

#!/usr/bin/python
#! -*- coding:utf-8 -*-

import re;

id_num = '440211199606030022'
id_pat = '(^\d{14}(\d|x)$|(^\d{17}(\d|x)$))'
id_str = re.match(id_pat,id_num)
print("Match: " + str(id_str.group()))


執行結果:

Match: 440211199606030022