开发者

VB.net Regex to C#

How would I convert this to C# from VB.net. I tried the online converters but I got errors when I put it in my project.

Dim regexinfo As String = String.Empty
Dim p = "\[news\](?<info>.*?)\[/news\]"
Dim Matches = Regex.Matches(re开发者_Python百科sponse, 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


I'm guessing it's the "Match" variable named the same as it's type that's causing problems. This should do what you want:

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;

This code is functionally equivalent to your original VB.Net, even though it's only 3 lines instead of 10 (and it could easily be just 1).

For example, the "if" condition in the original code was not needed, as the Matches() function will return an empty collection rather than null and ?? string.Empty() snippet takes care of the not-found case. So even though the code changed, the behavior did not. This isn't a c# vs VB thing, though; VB.Net could do it in one line as well. You might want to make a further improvement by using FirstOrDefault() rather than LastOrDefault(). It's just that latter matches up with you original and former does not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜