Python中有幾個選項可以將整個輸入與正則表達式匹配。
的Python 2
在Python 2.x中,你可以使用
re.match(r'\d+$') # re.match anchors the match at the start of the string, so $ is what remains to add
或 - 避免在字符串中的最後\n
之前匹配:
re.match(r'\d+\Z') # \Z will only match at the very end of the string
或相同以上re.search
方法需要使用^
/\A
開始字符串錨點,因爲它不錨定matc在字符串的開頭H:
re.search(r'^\d+$')
re.search(r'\A\d+\Z')
注意\A
是一個明確的字符串開始錨,其行爲不能與任何改性劑(re.M
/re.MULTILINE
僅可以重新定義^
和$
行爲)重新定義。
Python 3中
所有在Python 2部分中所描述的那些情況下和一個更有用的方法,re.fullmatch
(也存在於PyPi regex
module):
如果整個串正則表達式匹配模式,返回一個相應的匹配對象。如果字符串不匹配模式,則返回None
;請注意,這與零長度匹配不同。
所以,編譯正則表達式後,只需使用適當的方法:
_rex = re.compile("\d+")
if _rex.fullmatch(s):
doStuff()
+1。如果可以,避免使用正則表達式。 – 2010-10-22 06:56:26
'\ d + $'應該足夠匹配 – Medorator 2014-08-27 17:55:50
'$'在換行符後面不起作用。參見're.match(r'^ \ d + $','4 \ n')'例如。 – Antimony 2015-12-20 20:08:31