views:

59

answers:

1
+1  Q: 

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(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
+6  A: 

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.

Joel Coehoorn
I need it to do it for every [news][/news] so I can basically get everything in between. [poster][/poster][date][/date][content][/content]
xZerox
@xzerox This code did what your original did. If you need to change that, it's a new issue. That's easy enough to do, though - just change it to return an IEnumerable and use a .Select() projection.
Joel Coehoorn