I have the following code. It's working as intended, but I just wanted to know if I can change the logic behind it to make it look simpler because I believe it's redundant.
It works like this: I fetch some data and then try to pass it through a regular expression. There are three possible outcomes:
- Data is fetched ok.
- Data is fetched but it doesn't contain a number. So another regex is passed.
- Data is not fetched. Same regex as 2) is passed. (this is what I believe could be simplified or optimised)
At first I thought that there could be a way of checking if the regular expression returns empty or not without throwing an exception, but (correct me if I'm wrong) there isn't such a thing... so that's why I included the try/catch. Without it, if the 3rd case is met, the IF returns an exception because it says that the m2[0].Groups[1].Captures[0].Value
is out of bounds, of course (because it's empty).
So... is there any way to make this look more optimised? Thank you very much!
string regexString = @" \.\.\. .*?>(.*?)<\/a>";
MatchCollection m2 = Regex.Matches(myInput, regexString, RegexOptions.Singleline);
try
{
if (m2[0].Groups[1].Captures[0].Value.All(Char.IsDigit) == false)
{
regexString = @"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""";
m2 = Regex.Matches(myInput, regexString);
}
}
catch (ArgumentException)
{
regexString = @"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""";
m2 = Regex.Matches(myInput, regexString);
}