python裡使用正規表示式的全匹配功能

2021-08-09 09:57:07 字數 1027 閱讀 3471

前面學習了很多匹配,比如搜尋任意位置的search()函式,搜尋邊界的match()函式,現在還需要學習乙個全匹配函式,就是搜尋的字元與內容全部匹配,它就是fullmatch()函式。例子如下:

#python 3.6

#蔡軍生 

##import re

text = 'this is some text -- with punctuation.'

pattern = 'is'

print('text       :', text)

print('pattern    :', pattern)

m = re.search(pattern, text)

print('search     :', m)

s = re.fullmatch(pattern, text)

print('full match :', s)

text = 'is'

print('text       :', text)

s = re.fullmatch(pattern, text)

print('full match :', s)

text = 'iss'

print('text       :', text)

s = re.fullmatch(pattern, text)

print('full match :', s)

結果輸出如下:

text       : this is some text -- with punctuation.

pattern    : is

search     : <_sre.sre_match object; span=(2, 4), match='is'>

full match : none

text       : is

full match : <_sre.sre_match object; span=(0, 2), match='is'>

text       : iss

full match : none

python裡使用正規表示式的DOTALL標誌

正常的情況下,正規表示式裡的句號 是匹配任何除換行符之外的字元。但是有時你也想要求它連換行符也匹配,這時怎麼辦呢?其實不用急,可以使用dotall標誌,就可以讓它匹配所有字元,不再排除換行符了。如下例子 python 3.6 蔡軍生 import re text this is some text ...

python正規表示式及使用正規表示式的例子

正規表示式 正則表達用來匹配字串 正規表示式匹配過程 正規表示式語法規則 匹配除換行 n 外的任意字串 abcabc 轉義字元,使後乙個字元改變原來的意思 a c a c 字符集,對應的位置可以是字符集中任意字元,字符集中的字元可以逐個列出,也可以給出範圍,如 abc 或 a c 第乙個字元如果是 ...

python裡常用的正規表示式

1.使用者名稱import re 4到16位 字母,數字,下劃線,減號 if re.match r a za z0 9 abwc print 匹配 2.整數import re 正整數正則 if re.match r d 42 print 匹配 負整數正則 if re.match r d 42 pri...