【问题标题】:C# Regex locate groups missing a string?C# 正则表达式查找缺少字符串的组?
【发布时间】:2016-05-01 00:54:29
【问题描述】:

首先,我对 Regex 感到很糟糕。如果这很容易而且我只是想念它,请提前道歉:(

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

正则表达式匹配:

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

效果很好。

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

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

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

【问题讨论】:

  • 为什么不直接使用上面的正则表达式,然后foreach匹配,检查捕获的字符串是否包含return?这将非常准确且非常容易。

标签: c# regex regex-lookarounds locate


【解决方案1】:

看起来您可能正在分析 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}");
}

【讨论】:

  • 好吧……那……太酷了,我不会撒谎的。谢谢,我不知道这甚至存在!
  • 根据您的项目要求,您还可以使用相同的框架自动更新代码。
猜你喜欢
  • 1970-01-01
  • 2011-10-14
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
相关资源
最近更新 更多