I am trying to get a Regex that checks to make sure that a supplied int is 6 digits and it is not sequential nor contains all repeating digits whether in ascending or descending order. I don't really care if the regex returns a match for the non-allowed numbers, or returns a match of the original number if it is allowed.
So for example all of these numbers are what I would need to not pass validation with the regex:
- 123456
- 654321
- 069
- 456789
- 2435
- 444444
While numbers like these would pass:
- 044346
- 666605
- 042004
- 678853
Thanks.
EDIT: Appears regex is not appropriate for this. A lot of great answers and multiple are right, so I just went with who answered first, thank you all!
Regex may not be optimal for this, but it can be done with:
^
# fail if...
(?!
# repeating numbers
(\d) \1+ $
|
# sequential ascending
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5} \d $
|
# sequential descending
(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $
)
# match any other combinations of 6 digits
\d{6}
$
Use with /x
flag or (?x)
to preserve the readability.
You can also use the compact form (not recommended):
^(?!(\d)\1+$|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\d$)\d{6}$
Example usage (ideone):
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string re = @"(?x)
^
# fail if...
(?!
# repeating numbers
(\d) \1+ $
|
# sequential ascending
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5} \d $
|
# sequential descending
(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5} \d $
)
# match any other combinations of 6 digits
\d{6}
$
";
string[] numbers = { "102", "111111", "123456", "654321", "123455", "321123", "111112" };
foreach (var str in numbers)
{
Console.WriteLine(str);
Console.WriteLine(Regex.IsMatch(str, re) ? "\tMatched" : "\tFailed");
}
}
}
Output:
102
Failed
111111
Failed
123456
Failed
654321
Failed
123455
Matched
321123
Matched
111112
Matched
To be honest I don't think I got what you wanted, but following code works for your cases :)
var isMatch = Regex.IsMatch(input, "^[0-9]{6}$")
&& Regex.IsMatch(input, @"(([0-9]{1})\2+)")
&& input.Distinct().Count() > 1;
After several re-reading I think I got what you want :) See the following:
var isMatch = String.Join("", input.OrderBy(c => c)) != input
&& String.Join("", input.OrderByDescending(c => c)) != input
&& input.Distinct().Count() > 1
&& Regex.IsMatch(input, "^[0-9]{6}$");
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