5

我正在使用 ASP.NET MVC。

我需要一个只允许数字和字母的正则表达式,而不是空格或 ",.;:~^" 之类的东西。简单的数字和字母。

另一件事:2个字符不能连续重复。

所以我可以有 123123 但不能有 1123456。

我做到了:

Regex ER1 = new Regex(@"(.)\\1", RegexOptions.None);

Regex ER2 = new Regex(@"[A-Z0-9]", RegexOptions.IgnoreCase);

我无法用一种表达方式做到这一点,而且我仍然有一些角色通过。

这是我的整个测试代码:

class Program
{
    static void Main(string[] args)
    {
        string input = Console.ReadLine();

        Regex ER1 = new Regex(@"(.)\\1", RegexOptions.None);

        Regex ER2 = new Regex(@"[A-Z0-9]", RegexOptions.IgnoreCase);

        if (!ER1.IsMatch(input) && ER2.IsMatch(input))
            Console.WriteLine( "Casou");
        else
            Console.WriteLine( "Não casou");

            Console.ReadLine();
    }
}

我发现这些表达方式非常复杂,我很乐意在这方面得到一些帮助。

4

2 回答 2

11

让我们试试这个:

@"^(([0-9A-Z])(?!\2))*$"

解释:

^               start of string
 (              group #1
   ([0-9A-Z])   a digit or a letter (group #2)
   (?!\2)      not followed by what is captured by second group ([0-9A-Z])
 )*             any number of these
$               end of string

 

?!组称为负前瞻断言

 

LastCoder 的表达式是等价的)

于 2013-02-07T18:23:39.997 回答
2

像这样的东西应该工作

@"^(?:([A-Z0-9])(?!\1))*$"
于 2013-02-07T18:25:25.580 回答