Regex with 3 digits or 4 alphanumeric characters c#

I need to create a regex to validate if a string has a maximum of 3 digits or a maximum of 4 alphanumeric characters, for example those are valid:

This ones shouldn't be valid:

This is my code:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var text = "abcd";
        var newRegx = @"(^[0-9]{1,3}$)|(^[a-zA-Z0-9]{1,4}$)";    
        Regex rgx = new Regex(newRegx);
        
        Console.WriteLine ("regex: "+ newRegx);
        Console.WriteLine ("\n'"+(text="0000")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="01mk")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="k")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="987io")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="ff123")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="12")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="102n")+"' matches? "+ rgx.IsMatch(text) );
        Console.WriteLine ("\n'"+(text="1230")+"' matches? "+ rgx.IsMatch(text) );
    }
}

It produces this:

regex: (^[0-9]{1,3}$)|(^[a-zA-Z0-9]{1,4}$)
'0000' matches? True
'01mk' matches? True
'k' matches? True
'987io' matches? False
'ff123' matches? False
'12' matches? True
'102n' matches? True
'1234' matches? True

You can run it here: https://dotnetfiddle.net/vWyzD0

The problem is with last example (1234), it shouldn't be valid but my regex is assuming that it is an alphanumeric string and not a number, how can fix my regex?

Upvotes: 2

Views: 152

Answers (1)

depperm
depperm

Reputation: 10746

add negative lookahead (?!\d{4}) before the second part of or statement (^[0-9]{1,3}$)|(^(?!\d{4})[a-zA-Z0-9]{1,4}$) so that 4 digits aren't accepted

https://dotnetfiddle.net/CbGSlG

Upvotes: 3

Related Questions