Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式-检查嵌套循环的字符串_Python_Regex_String - Fatal编程技术网

Python正则表达式-检查嵌套循环的字符串

Python正则表达式-检查嵌套循环的字符串,python,regex,string,Python,Regex,String,输入:包含一段代码的字符串 目标:查找字符串输入是否包含:- 嵌套循环 e、 g 而 我无法获得嵌套循环的正则表达式 如有任何帮助/建议,将不胜感激 基于@Kevin的建议 我可以用 def hasRecursion(tree): for node in [n for n in ast.walk(tree)]: nodecls = node.__class__ nodename = nodecls.__name__

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

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

嵌套循环 e、 g

我无法获得嵌套循环的正则表达式


如有任何帮助/建议,将不胜感激

基于@Kevin的建议

我可以用

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))

谢谢@Kevin

请参阅和,以获得如何提出好问题的指导。请在你的问题中包括你迄今为止所做的尝试。因此,没有代码工厂来编写代码。看见请包括一个。我认为这个项目比你可能意识到的要雄心勃勃得多。谢谢@BoarGules有没有更简单的方法来检查嵌套循环。因为我目前只使用简单的文本搜索“for”和“while”来检查循环。但不知道如何对嵌套循环执行同样的操作。正则表达式的功能不足以解析Python程序,因为Python程序可以包含任意嵌套的括号,而使用正则表达式是无法匹配的。相反,请尝试使用ast.parse获取程序的语法树。您可以遍历该树并确定它是否包含两个连续的For节点。非常感谢@Kevin。我试试看。
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))