c#正则表达式,允许数字和字母不起作用

时间:2013-02-07 18:19:24

标签: c# regex asp.net-mvc expression

我正在使用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();
    }
}

我发现这些表达非常复杂,我很乐意为此提供一些帮助。

2 个答案:

答案 0 :(得分: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

?!组称为negative lookahead assertion

LastCoder的表达式是等效的)

答案 1 :(得分:2)

这样的事情应该有效

@"^(?:([A-Z0-9])(?!\1))*$"