C#Regex找到缺少字符串的组?

时间:2016-05-01 00:54:30

标签: c# regex regex-lookarounds locate

首先,我对正则表达式很可怕。如果事情变得容易而且我只是错过它,那就预先道歉:(

好的,所以我想说我要解析我的源代码,并找到我所有的私有函数。此外,假设我想获得整个代码块,以便我可以检查它。

正则表达式匹配:

Private Function[\s\S]*?End Function

效果很好。

现在,如果我想查找缺少Return语句的所有函数,该怎么办?我似乎无法弄明白这一点(见上文re:正则表达式,我并不相处得很好)。

有人介意我指向正确的方向吗?我正在使用正则表达式的.NET实现,如果这很重要(似乎 - 我找到的Java示例似乎都没有用!)

我正在使用regexstorm.net进行测试,如果重要的话:)谢谢!

1 个答案:

答案 0 :(得分:0)

看起来您可能正在分析Visual Basic。您可以使用Microsoft的代码分析工具(Roslyn)来解析代码并分析不同的部分。这将防止必须寻找不同代码文件的不同语法接受。以下示例代码将确定Function是私有的还是具有as子句。

string code = @"
    Function MyFunction()
    End Function

    Private Function MyPrivateFunction()
    End Function

    Function WithAsClause() As Integer
    End Function
    ";

// Parse the code file.
var tree = VisualBasicSyntaxTree.ParseText(code);

var root = tree.GetCompilationUnitRoot();

// Find all functions in the code file.
var nodes = root.DescendantNodes()
    .Where(n => n.Kind() == SyntaxKind.FunctionBlock)
    .Cast<MethodBlockSyntax>();

foreach (var node in nodes)
{
    // Analyze the data for the function.
    var functionName = node.SubOrFunctionStatement.Identifier.GetIdentifierText();
    bool isPrivate = node.BlockStatement.Modifiers.Any(m => m.Kind() == SyntaxKind.PrivateKeyword);
    var asClause = node.SubOrFunctionStatement.AsClause;
    bool hasAsClause = asClause != null;

    Console.WriteLine($"{functionName}\t{isPrivate}\t{hasAsClause}");
}
相关问题