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