C # regexes assume numbers and letters don't work

I am using ASP.NET MVC.

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

Other: two characters cannot be repeated sequentially.

So, I can have 123123, but not 1123456.

I got to:

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

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

I could not do everything in one expression, and I still have some characters going through.

Here is my entire testing code:

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 would be very happy to help with this.

+5
source share
2 answers

Let's try this:

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

Explanations:

^               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 negative expectation .

 

(LastCoder expression is equivalent)

+11

-

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

All Articles