正则表达式模式ValueError

时间:2013-01-02 11:21:59

标签: python regex

在下面的代码中,我尝试匹配数字,这些数字可以是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!!"

1 个答案:

答案 0 :(得分: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 found 5次。