Reputation: 29
I am trying to match results that contain either 4 numbers or 6 numbers, nothing else.
I have tried using (?!5)
or (?!\d)
at the end but it still matches input of 5 numbers, I feel like I have tried everything.
It returns the second test as a match.
Tests:
[Test]
[TestCase("1234", Result=true)]
[TestCase("12345", Result=false)]
[TestCase("a234", Result=false)]
[TestCase("", Result=false)]
Code:
using System.Text.RegularExpressions;
public class Program
{
public static bool ValidatePIN(string pin)
{
string pattern = @"[1-9]{4}|[1-9]{6}(?!5)";
Regex rg = new Regex(pattern);
Match match = rg.Match(pin);
if (match.Success) {
return true;
} else {
return false;
}
}
}
Upvotes: 1
Views: 108
Reputation: 821
public static bool IsValid(string s)
{
return Regex.IsMatch(s, "^([\\d]{4}|[\\d]{6})$");
}
Upvotes: 1
Reputation: 186668
It seems, you should use achors
^([1-9]{4}|[1-9]{6})$
here
^ - beginning of the string
([1-9]{4}|[1-9]{6}) - either 4 or 6 digits
$ - end of the string
You can wrap it into the method as
public static bool ValidatePIN(string pin) =>
Regex.IsMatch(pin, @"^([1-9]{4}|[1-9]{6})$");
Another possibility is Linq:
public static bool ValidatePIN(string pin) =>
pin != null &&
(pin.Length == 4 || pin.Length == 6) &&
pin.All(c => c >= '0' && c <= '9');
Upvotes: 2