简体   繁体   English

正则表达式不匹配字符串C#中的连续数字

[英]Regex to not match consecutive numbers in a string c#

My requirement is to enforce a password policy which contains a rule to not have consecutive numbers ie "pass1234","abc12","12tab" etc. should be not allowed. 我的要求是强制执行密码策略,该策略包含不具有连续数字的规则,即不允许使用“ pass1234”,“ abc12”,“ 12tab”等。 my current regex is: 我当前的正则表达式是:

if(!Regex.IsMatch(password,
                    @"^(?!(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0))\d{1,}|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8))\d{1,})[a-zA-Z\d]+$")))

But the above regex matches strings that start with numbers ie "12abc", "12pass" but not the strings that contain numbers in between the string like "ab12pass","pass1234" etc. 但是上面的正则表达式匹配以数字开头的字符串,例如“ 12abc”,“ 12pass”,但不匹配在字符串之间包含数字的字符串,例如“ ab12pass”,“ pass1234”等。

Here's how I would do it without using regular expressions if you really meant you don't want consecutive increasing or decreasing numbers. 如果您确实想不想连续增加或减少数字,那么我将在不使用正则表达式的情况下执行以下操作。

private static bool NoConsecutiveIncreasingOrDecreasingNumbers(string str)
{
    if (string.IsNullOrWhiteSpace(str))
        return true;

    char prev = str[0];
    for (int i = 1; i < str.Length; i++)
    {
        char current = str[i];
        if ('0' < current && current < '9' && 
            '0' < prev && prev < '9' && 
            (prev + 1 == current || current + 1 == prev ))
            return false;
        prev = current;
    }

    return true;
}

Just remove that last condition in the if if you really did mean any consecutive numbers. 只是删除在最后一个条件的if ,如果你真的是指任何连续的数字。

Here is a Regex to detect if there are ascending or descending numbers. 这是一个正则表达式,用于检测数字是升序还是降序。

^((?:0(?=1|$))?(?:1(?=2|$))?(?:2(?=3|$))?(?:3(?=4|$))?(?:4(?=5|$))?(?:5(?=6|$))?(?:6(?=7|$))?(?:7(?=8|$))?(?:8(?=9|$))?9?|(?:9(?=8|$))?(?:8(?=7|$))?(?:7(?=6|$))?(?:6(?=5|$))?(?:5(?=4|$))?(?:4(?=3|$))?(?:3(?=2|$))?(?:2(?=1|$))?(?:1(?=0|$))?0?)$

正则表达式可视化

Debuggex Demo Debuggex演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM