首页 > 解决方案 > 如何使用正则表达式使两个子组出现相同的次数?

问题描述

在正则表达式中:我在匹配以下语言时遇到问题:

 L = {((aa) repeat n times)(b repeat n times) | n >=1 }

我试图这样做(aa)+b+,但这不能保证aa并且b发生相同的次数。

有什么简单的方法可以做到这一点(在python中?)?谢谢。

标签: pythonregex

解决方案


如果你被允许,我推荐一个简单的递归下降方法。

您可以同时aa从正面和b背面移除。

def foo(s):
  if s == "":
    return True
  if s.startswith('aa') and s.endswith('b'):
    return foo(s[2:-1])
  else:
    return False

推荐阅读