首先,我很害怕Regex。如果这太容易了,我只是错过了,请提前道歉:(
好吧,假设我正在解析我的源代码,并找到我所有的私有函数。此外,假设我想得到整个代码块,这样我就可以检查它
Regex匹配:
Private Function[sS]*?End Function
效果很好。
现在,如果我想查找所有缺少Return语句的函数,该怎么办?我似乎无法理解这一点(参见上面的re:regex,我相处得并不好)。
有人介意给我指正确的方向吗?我正在使用。NET实现正则表达式,如果这很重要的话(而且似乎是这样——我发现的Java示例似乎都不起作用!)
我正在使用regexstorm.net进行测试,如果重要的话:)谢谢!
看起来您可能正在分析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}");
}