正则表达式模式ValueError

Raj*_*eev 0 python regex

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

我得到一个错误

ValueError: Cannot process flags argument with a compiled pattern
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

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!!"
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 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)
Run Code Online (Sandbox Code Playgroud)

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

matchObj = p_number.search(a)
Run Code Online (Sandbox Code Playgroud)

您的完整脚本将变为:

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!!"
Run Code Online (Sandbox Code Playgroud)

并打印match found5次.