用正则表达式检查整个字符串

dut*_*utt 13 python regex

我正在尝试检查字符串是否为数字,因此正则表达式"\ d +"似乎很好.然而,由于某些原因,正则表达式也符合"78.46.92.168:8000",我不想要,一点点代码:

class Foo():
    _rex = re.compile("\d+")
    def bar(self, string):
         m = _rex.match(string)
         if m != None:
             doStuff()
Run Code Online (Sandbox Code Playgroud)

输入ip地址时调用doStuff().我有点困惑,"怎么样".或":"匹配"\ d"?

eum*_*iro 26

\d+匹配的数字任意正数范围内的字符串,因此它匹配的第一个78和成功.

使用^\d+$.

或者,甚至更好: "78.46.92.168:8000".isdigit()


Tim*_*ker 12

re.match()始终匹配字符串的开头(与之不同re.search()),但允许匹配在字符串结束之前结束.

因此,你需要一个锚:_rex.match(r"\d+$")会工作.

更明确的是,您也可以使用_rex.match(r"^\d+$")(这是多余的)或者只是re.match()完全删除而只是使用_rex.search(r"^\d+$").


gho*_*g74 7

\Z matches the end of the string while $ matches the end of the string or just before the newline at the end of the string, and exhibits different behaviour in re.MULTILINE. See the syntax documentation for detailed information.

>>> s="1234\n"
>>> re.search("^\d+\Z",s)
>>> s="1234"
>>> re.search("^\d+\Z",s)
<_sre.SRE_Match object at 0xb762ed40>
Run Code Online (Sandbox Code Playgroud)


pro*_*ick 5

从更改\d+^\d+$


Wik*_*żew 5

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
Run Code Online (Sandbox Code Playgroud)

或 - 避免\n在字符串中的final之前匹配:

re.match(r'\d+\Z') # \Z will only match at the very end of the string
Run Code Online (Sandbox Code Playgroud)

或者与上面相同的re.search方法需要使用^/ \Astart-of-string锚,因为它不会在字符串的开头锚定匹配:

re.search(r'^\d+$')
re.search(r'\A\d+\Z')
Run Code Online (Sandbox Code Playgroud)

请注意,这\A是一个明确的字符串起始锚点,其行为不能使用任何修饰符重新定义(re.M/ re.MULTILINE只能重新定义^$行为).

Python 3

Python 2部分中描述的所有这些情况以及一个更有用的方法re.fullmatch(也存在于PyPi regex模块中):

如果整个字符串与正则表达式模式匹配,则返回相应的匹配对象.None如果字符串与模式不匹配则返回; 请注意,这与零长度匹配不同.

因此,在编译正则表达式之后,只需使用适当的方法:

_rex = re.compile("\d+")
if _rex.fullmatch(s):
    doStuff()
Run Code Online (Sandbox Code Playgroud)