I am working on a project that parses an incoming text file. I am learning C# as I go. My current method for picking out the information I need is something like:
string MyMatchString = @"a pattern to match";
Match MyMatch = Regex.Match(somestringinput, MyMatchString);
if (MyMatch.Succes)
{
DoSomething(MyMatch.Value);
}
I am doing a lot of that. I’d like to be able to combine the match and the test for success in one step. Looking through the Class listings, Regex has an IsMatch() method, but it doesn’t appear that I can access the matched value (assuming it is successful). I think I need a Match instance for that. I tried
if ((Match MyMatch = Regex.Match(somestringinput, MyMatchString).Success)
but of course got a compile error.
I am thinking a static method that takes the match pattern and the input then returns a bool is the way to go. Then I can just test for success, and if so grab the matched value.
Well you can write an extension method for Regex which would give you some power. The trick is doing it without running the regex match twice, which could be a problem for your performance (note: this hasn’t been tested, and it differs from your idea in that it requires a ready-made Regex object to work).
So you’d do something like
You might prefer to just return null in the failure case and the string otherwise and dispense with the boolean and the output parameter.