Python匹配xx xxxx数字-不准确的结果



我在正则表达式方面很弱。

我正在尝试匹配一个字符串,它可能如下所示:

12-1234 *string*
12 1234 *string*

12 123 *string*
12-1234 *string*

只要在给定的字符串中找到该模式,那么它就应该通过…

我认为这应该足够了:

    a = re.compile("^d{0,2}[- ]d{0,4}$")
    if a.match(dbfull_address):
        continue

然而,我仍然得到不准确的结果:

12字符串

我想我需要帮助我的正则表达式:D

^d{0,2}[- ]d{0,4}$

允许空格/短划线周围有零位数字,因此您可能希望使用d{1,2}[- ]d{1,4}

此外,您应该删除$锚点,除非您只想匹配第二个数字后面没有任何内容的行。

^锚也没有必要,因为Python的.match()方法将正则表达式匹配隐式锚定到字符串的开头。

reobj = re.compile(r"^[d]{0,2}[s-]+[d]{0,4}.*?$", re.IGNORECASE | re.MULTILINE)

Options: dot matches newline; case insensitive; ^ and $ match at line breaks
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single digit 0..9 «[d]{2}»
   Exactly 2 times «{2}»
Match the regular expression below and capture its match into backreference number 1 «(.|*)?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match either the regular expression below (attempting the next alternative only if this one fails) «.»
      Match the character “.” literally «.»
   Or match regular expression number 2 below (the entire group fails if this one fails to match) «*»
      Match the character “*” literally «*»
Match the regular expression below and capture its match into backreference number 2 «([d]{2})?»
   Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
   Match a single digit 0..9 «[d]{2}»
      Exactly 2 times «{2}»

最新更新