1

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
1
  • Can you be more specific regarding the errors you got? Commented Jul 26, 2010 at 2:05

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.