我如何将其从 VB.net 转换为 C#。我尝试了在线转换器,但在将其放入我的项目时出现错误。
Dim regexinfo As String = String.Empty
Dim p = "\[news\](?<info>.*?)\[/news\]"
Dim Matches = Regex.Matches(response, p, RegexOptions.IgnoreCase Or RegexOptions.Singleline)
If Matches IsNot Nothing AndAlso Matches.Count > 0 Then
For Each Match As Match In Matches
If Match.Groups("info").Success Then
regexinfo = (Match.Groups("info").Value)
End If
Next
End If
请您参考如下方法:
我猜是“Match”变量的名称与其类型相同导致了问题。这应该做你想做的:
var p = @"\[news\](?<info>.*?)\[/news\]";
var Matches = Regex.Matches(response, p, RegexOptions.IgnoreCase | RegexOptions.Singleline);
string regexinfo = Matches.LastOrDefault(m=>m.Groups("info").Success) ?? string.Empty;
此代码在功能上等同于您的原始 VB.Net,即使它只有 3 行而不是 10 行(而且很容易只有 1 行)。
例如,原始代码中的“if”条件是不需要的,因为 Matches() 函数将返回一个空集合而不是 null 和 ?? string.Empty() 片段负责处理未找到的情况。所以即使代码改变了,行为也没有改变。不过,这不是 c# vs VB 的事情; VB.Net 也可以在一行中完成。您可能希望使用 FirstOrDefault() 而不是 LastOrDefault() 来进一步改进。只是后者和你原来的匹配,前者不匹配。
