Python regex findall()返回不需要的子字符串(包括正确答案)

时间:2019-04-22 16:02:53

标签: python regex

我必须编写一个python函数,该函数获取一行代码作为输入,如果该行包含三元运算符(并对其进行计数!),则返回true,否则返回false。我编写了一些正则表达式版本,这些版本在此网站https://regexr.com/上运行良好,但是例如在Google Colab上,它们都不起作用。

def ternaryOp(line):
  found_operator=re.findall(r'(((=|==|<|>|<=|>=|!=)[\s\t]*)?[\s\t]*.+[\s\t]*\?[\s\t]*((.+:.*)|(.*:.+)))',line)
  if found_operator:
      print(len(found_operator))
      print(found_operator)
      return True
  else:
    return False


ternaryOp('category=age<18?child:adult')

预期结果:

1
[('category=age<18?child:adult')]
True

实际结果:

6
[('category=age<18?child:adult', '', '', 'child:adult', 'child:adult', '')]
True

2 个答案:

答案 0 :(得分:0)

它正在做exactly what it's supposed and documented to do

  

如果模式中存在一个或多个组,则返回一个组列表;如果模式包含多个组,则这将是一个元组列表。空匹配项包含在结果中。

您的正则表达式有6个捕获组,因此每个匹配项都是6个元组,其中元组的每个元素都是一个捕获组。要么使用它,要么对您不特别在意的组使用非捕获组((?:pattern)),或者使用re.finditer产生 match对象,从而变得更加丰富和更灵活的结果。

顺便说一句,您的工作效率很低,如果您只想知道可以使用re.matchre.search在字符串中找到模式,那么您在此处发布的代码不需要findall的功能,因为您只是检查它是否发现了任何东西。

答案 1 :(得分:0)

我想我已经找到了适合我的解决方案。谢谢大家!

re.findall(r'(?:(?:=|==|<|>|<=|>=|!=)?[\s\t]*[\s\t]*[^?:]+[\s\t]*\?[\s\t]*(?:.*?:[^ ]*))')