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

时间:2014-04-16 07:54:23

标签: python regex string

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

我正在尝试匹配一个可能像下面这样的字符串的字符串:

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 string

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

2 个答案:

答案 0 :(得分:2)

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

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

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

由于Python的^方法隐式地将正则表达式匹配锚定到字符串的开头,因此.match()锚也是不必要的。

答案 1 :(得分:1)

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}»