6位int的正则表达式,不能是连续或重复的数字?

Sve*_*ang 3 .net c# regex

我试图得到一个正则表达式,检查以确保提供的int是6位数,它不是顺序的,也不包含所有重复的数字,无论是按升序还是降序.我真的不在乎正则表达式是否返回非允许数字的匹配项,或者如果允许则返回原始数字的匹配项.

所以例如所有这些数字都是我不需要通过正则表达式验证的:

  • 123456
  • 654321
  • 069
  • 456789
  • 2435
  • 444444

虽然这些数字会通过:

  • 044346
  • 666605
  • 042004
  • 678853

谢谢.

编辑:出现正则表达式不适合这个.很多很好的答案和多个是正确的,所以我只是跟谁先回答,谢谢大家!

Qta*_*tax 5

正则表达式可能不是最佳选择,但它可以通过以下方式完成:

^
# 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}
$
Run Code Online (Sandbox Code Playgroud)

/xflag (?x)一起使用或保持可读性.您也可以使用紧凑形式(不推荐):

^(?!(\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}$
Run Code Online (Sandbox Code Playgroud)

用法示例(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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

102
    Failed
111111
    Failed
123456
    Failed
654321
    Failed
123455
    Matched
321123
    Matched
111112
    Matched
Run Code Online (Sandbox Code Playgroud)