如何使用正则表达式查找带有大写字母的语句?

时间:2019-03-07 14:51:38

标签: python regex

我想在我的整个Python代码库中搜索包含大写字母的函数定义(包括函数名称,参数名称和注释表达式)。因此应捕获以下代码:

示例1

def Foobar(arg1: expression, 
           arg2: expression, 
           *args: expression, 
           **kwargs: expression)->expression:

示例2

def foobar(arg1: expression, 
           Arg2: expression, 
           *args: expression, 
           **kwargs: expression)->expression:

由于语句中可以有多个:,所以我认为这可能很难。如果我们可以假设没有注释,该怎么办。例如,

def foobar(arg1, 
           Arg2, 
           *args, 
           **kwargs):

2 个答案:

答案 0 :(得分:1)

有点粗糙,但这应该可以工作:

def [^A-Z]*[A-Z]+[^)]*

答案 1 :(得分:1)

我建议您为此使用pylint而不是使用正则表达式。如果您真的想自己使用,可以使用下面的代码。

import re

regex = r"def (?P<func_name_and_args>\w*\(.+?\))"

with open(/path/to/file/, 'r') as test_file:
    lines = test_file.readlines()

    matches = re.finditer(regex, lines, re.DOTALL | re.MULTILINE)
    for match in matches:
        group = match.group('func_name_and_args')
        if any(char != char.lower() for char in group):
            print(group)

您可以使用https://regex101.com/r/BMniq9/1

对其进行测试。