簡體   English   中英

c#正則表達式,允許數字和字母不起作用

[英]c# regular expressions, allow numbers and letters only not working

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

我發現這些表達非常復雜,我很樂意為此提供一些幫助。

我們試試這個:

@"^(([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

?! group被稱為負前瞻斷言

LastCoder的表達式相同)

這樣的事情應該有效

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM