0

在下面的代码中,我试图匹配数字,可以是 16 位或 15 位数字,并且可能有空格或-在每 4 位数字之间。

我收到一个错误

ValueError: Cannot process flags argument with a compiled pattern

我究竟做错了什么?

import re

p_number = re.compile(r'(\d{15}|\d{16}|\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4})')
c=["1234567891234567","123456789123456","1234 5678 9123 4567","1234-5678-9123-4567","1234567891111111tytyyyy"]

for a in c:
  #re.search(c,p_number,flag=0)
  matchObj = re.search( p_number , a, re.M|re.I)
  if matchObj:
     print "match found"
  else:
     print "No match!!"
4

1 回答 1

7

您需要将标志传递给.compile()调用:

p_number = re.compile(r'(\d{15}|\d{16}|\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4})', re.M|re.I)

你可以调用.search()编译后的模式:

matchObj = p_number.search(a)

您的完整脚本将变为:

import re

p_number = re.compile(r'(\d{15}|\d{16}|\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4})', re.M|re.I)
c=["1234567891234567","123456789123456","1234 5678 9123 4567","1234-5678-9123-4567","1234567891111111tytyyyy"]

for a in c:
    matchObj = p_number.search(a)
    if matchObj:
        print "match found"
    else:
        print "No match!!"

并打印match found5 次。

于 2013-01-02T11:24:39.463 回答