I am trying to come up with an expression that checks for given integer if its third digit from right-to-left is 5. What I managed so far is this:
string input = "5";
if (Regex.IsMatch(input[2].ToString(), "[5]"))
{
System.Console.WriteLine("yes");
}
else
System.Console.WriteLine("no");
Got 2 problems with this:
First it counts from left to the right not from right to the left and second when the number is less than 3 digits like in this case return out of range exception.
Use a numerical way. If the number is greater than 99 and n is your integer then use
(n / 100) % 10 == 5
n / 100 removes the last two digits (integer division truncates) and the % 10 extracts the now rightmost digit. Check if it's 5 or not.
It will be much faster than using a regular expression.
Bathsheba's answer is much better, but if you would like to use a regular expression, I believe this one will fit your needs: ^\d+(?:[5](\d){2})$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With