【问题标题】:Python regex - check String for nested loopsPython 正则表达式 - 检查嵌套循环的字符串
【发布时间】:2023-03-03 13:30:01
【问题描述】:

输入:包含一段代码的字符串。

目标:查找输入的字符串是否包含:-

  • 嵌套循环

例如

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  for y in x:
     print(y)

当...为

我无法专门获取嵌套循环的正则表达式。

任何帮助/建议将不胜感激!

【问题讨论】:

  • 请参阅How do I ask a good questionHelp Center,了解如何提出一个好的问题。请在您的问题中包含您迄今为止尝试过的内容。 SO 不是编写代码的“代码工厂”。见How do I ask a good question。请包含Minimal, Reproducible Example
  • 我认为这个项目比你想象的要雄心勃勃。
  • 谢谢@BoarGules 是否有一些更简单的方法来检查嵌套循环。因为我目前正在通过简单的文本搜索“for”和“while”来检查循环。但不知道如何为嵌套循环做同样的事情。
  • 正则表达式的功能不足以解析 Python 程序,因为 Python 程序可以包含任意嵌套的括号,这是众所周知的使用正则表达式无法匹配的。相反,尝试使用ast.parse 来获取程序的语法树。您可以遍历树并确定它是否包含两个连续的For 节点。
  • 非常感谢@Kevin。我会试试看。

标签: python regex string


【解决方案1】:

基于@Kevin 的“ast.parse”建议

我可以使用

def hasRecursion(tree):
    for node in [n for n in ast.walk(tree)]:
            nodecls = node.__class__
            nodename = nodecls.__name__
            if isinstance(node, (ast.For, ast.While)):
                for nodeChild in node.body:     
                    #node.body Or ast.iter_child_nodes(node)
                    if isinstance(nodeChild, (ast.For, ast.While)):
                        return True
return False




expr="""
for i in 3:
   print("first loop")
   for j in i:
        print("nested loop")

print('normal')
"""

tree = ast.parse(expr, mode="exec")

print(hasRecursion(tree))

ast.parse code examples

感谢@Kevin

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 2017-03-15
    相关资源
    最近更新 更多