Regex to test at most 2 numbers and at most 4 alphabets in a string of length 6

  • The maximum line length is 6.
  • The string must be no more than 2 digits
  • The string must contain no more than 4 alphabets

So the following examples should match

abcd22

a1cd3d

11acde

a1c

1ad

      

+2


source to share


5 answers


What you want is really not possible in regex, because cant count regex that would be required here. In fact, regular expressions seem to be able to read characters in direct sequence, for example. in this case:

/x{2,3}/ # 2 or 3 ‘x’s

      

... but that doesn't really count, because its just a shortcut to that expression:



/xxx?/

      

i.e. 2 x

s followed by an optional third.

Your expression, on the other hand, would have to keep track of two different counters throughout the machine that the expression represents. This just isn't possible with classic regexes (and it's still very difficult to use more modern regex incarnations that use pushdown automata to persist state).

+1


source


I would do an OR test on a regex group:

/^[a-z0-9]{0,6}$/ # at most 6 characters
/([a-z].*){5}/    # more than 4 letters
/(\d.*){3}/       # more than 2 digits

      



So:

if ( /^[a-z0-9]{0,6}$/ and !( /([a-z].*){5}/ or /(\d.*){3}/ ) ) {
  print "valid";
}

      

+2


source


I would not use a regular expression for this, except, perhaps, to check alphanumeric / less than 6: /^[0-9a-z]{1,6}$/i

. But counting conditions, while technically feasible with regular expressions, improve with simple counting.

So I would

  • Check if it matches a regular expression /^[0-9a-z]{1,6}$/i

  • Then use a for loop to count attachments chararcter classe
+1


source


Regular expressions are not good for tracking state. You could do it with a regex, but it would be much easier to use a simple calculator and small regex program:

bool IsValid(string s)
{
   int numInts = 0;
   int numChars = 0;
   Regex isDigit = new Regex(@"\d");
   Regex isChar  = new Regex(@"[a-zA-Z]"); // NOTE: will NOT catch non english letters

   if (s.Length() <= 6) 
   {
       return false;
   }

   foreach (char c in s)
   {
       if (isDigit.IsMatch(c)) 
       {
           ++numInts;
       }
       if (isChar.IsMatch(c))
       {
           ++numChars;
       }
   }

   return numInts == 2 && numChars == 4;

      

}

Create / rename args to suit your needs.

Of course, if you want to be like C, you can do a numeric comparison to char, but that will take you further away from a robust and reliable solution.

0


source


You can do this using negative imagery.

(?!\d{5})(?![a-z]{3})[a-z0-9]{1,6}

      

(?!\d{5})

cannot find 5 or more digits

(?![a-z]{3})

fails if 3 or more characters are found

If both of them pass, we will finally check that there is between 1 and 6 alphanumeric characters (?!\d{5})(?![a-z]{3})[a-z0-9]{1,6}

0


source







All Articles