代码之家  ›  专栏  ›  技术社区  ›  dutt

用regex检查整个字符串

  •  11
  • dutt  · 技术社区  · 14 年前

    我正在检查字符串是否是数字,所以regex“\d+”看起来不错。不过,regex也适合“78.46.92.168:8000”,这是我不想看到的,一点代码:

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

    当输入IP地址时调用dostuff()。我有点困惑,“.”或“:”如何匹配“\d”?

    5 回复  |  直到 8 年前
        1
  •  25
  •   Antimony    9 年前

    \d+ 匹配任何正数 在内部 你的字符串,所以它与第一个匹配 78 成功了。

    使用 ^\d+$ .

    或者,更好的是: "78.46.92.168:8000".isdigit()

        2
  •  12
  •   Uli Köhler    11 年前

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

    因此,您需要一个锚: _rex.match(r"\d+$") 会有用的。

    更明确地说,您还可以使用 _rex.match(r"^\d+$") (这是多余的)或者直接放下 重新匹配() 一起用吧 _rex.search(r"^\d+$") .

        3
  •  7
  •   Uli Köhler    11 年前

    \Z 匹配字符串的结尾,而 $ 匹配字符串的结尾或字符串结尾处的换行符之前,并在中显示不同的行为 re.MULTILINE . 见 the syntax documentation 有关详细信息。

    >>> s="1234\n"
    >>> re.search("^\d+\Z",s)
    >>> s="1234"
    >>> re.search("^\d+\Z",s)
    <_sre.SRE_Match object at 0xb762ed40>
    
        4
  •  5
  •   prostynick    14 年前

    把它从 \d+ ^\d+$

        5
  •  5
  •   Graham francescalus    8 年前

    在python中有几个选项可以将整个输入与regex匹配。

    巨蟒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 字符串开始锚定,因为它不会在字符串开始锚定匹配项:

    re.search(r'^\d+$')
    re.search(r'\A\d+\Z')
    

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

    巨蟒3

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

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

    因此,在编译regex之后,只需使用适当的方法:

    _rex = re.compile("\d+")
    if _rex.fullmatch(s):
        doStuff()