c# - 不能是连续或重复数字的 6 位整数的正则表达式?

标签 c# .net regex

我正在尝试获取一个正则表达式来检查以确保提供的 int 是 6 位数字,并且它不是连续的,也不包含所有重复的数字,无论是按升序还是降序排列。我真的不在乎正则表达式是否返回了不允许的数字的匹配项,或者返回了原始数字的匹配项(如果允许的话)。

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

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

虽然像这样的数字会通过:

  • 044346
  • 666605
  • 042004
  • 678853

谢谢。

编辑:似乎正则表达式不适用于此。很多很棒的答案,而且很多都是正确的,所以我只选择第一个回答的人,谢谢大家!

最佳答案

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

^
# 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}
$

/x 标志或 (?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}$

用法示例 ( 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");
        }
    }
}

输出:

102
    Failed
111111
    Failed
123456
    Failed
654321
    Failed
123455
    Matched
321123
    Matched
111112
    Matched

关于c# - 不能是连续或重复数字的 6 位整数的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9519640/

相关文章:

.net - 如何在网页上实现文件上传进度条?

javascript - 使用数字短格式日期模式检测特定字符串结构

regex - 如何对所有非 ASCII 字符进行 grep?

c# - 此平台不支持 Diffie-Hellman 加密算法

c# - 从 c# datetime 到 xsd :datetime

.net - asp.net成员的用户createdate

javascript - 精确匹配字符串

c# - 绘制圆后如何将其视为控件? - 移动和选择形状

c# - Angular 9 组件和 .NET Core 应用程序未作为 SPA 运行

c# - ASP.Net 处理程序 Request.Files 始终为空