Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using ASP.NET MVC.

I need a regular expression that allows only numbers and letters, not spaces or ",.;:~^" anything like that. Plain numbers and letters.

Another thing: 2 characters can't repeat consecutively.

So I can have 123123 but not 1123456.

I got as far as to:

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

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

I could not make it all in one expression and I still have some characters passing through.

Here is my entire code for testing:

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();
    }
}

I find these expressions quite complex and I'd be really happy to have some help with this.

like image 496
Cesar Zapata Avatar asked Feb 07 '13 18:02

Cesar Zapata


2 Answers

Let's try this:

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

Explained:

^               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

 

The ?! group is called a negative lookahead assertion.

 

(LastCoder's expression is equivalent)

like image 72
Pavel Anossov Avatar answered Sep 29 '22 00:09

Pavel Anossov


Something like this should work

@"^(?:([A-Z0-9])(?!\1))*$"
like image 38
Louis Ricci Avatar answered Sep 29 '22 00:09

Louis Ricci