Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in php - letters and numbers with limited length

How do I make a regex that enforces:

  • letters AND numbers (at least 1 of each)
  • min and max length (10 to 50)
  • nothing other than letters or numbers

when using a php preg_match?


Here's what I got:

 ^[A-Za-z0-9]{10,50}$

It seems to do everything except enforce letters AND numbers.

like image 484
Ibrahim Avatar asked Oct 18 '16 04:10

Ibrahim


People also ask

How do you restrict length in regex?

By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.

What does * do in regex?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.

What does D+ mean in regex?

\d is a digit (a character in the range [0-9] ), and + means one or more times. Thus, \d+ means match one or more digits. For example, the string "42" is matched by the pattern \d+ .


1 Answers

Do:

^(?=.*(?:[A-Za-z].*\d|\d.*[A-Za-z]))[A-Za-z0-9]{10,50}$
  • (?=.*(?:[A-Za-z].*\d|\d.*[A-Za-z])) is zero width positive lookahead, this makes sure there is at least one letter, and one digit present

  • [A-Za-z0-9]{10,50} makes sure the match only contains letters and digits

Demo


Or even cleaner, use two lookaheads instead of OR-ing (thanks to chris85):

^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9]{10,50}$
like image 179
heemayl Avatar answered Oct 02 '22 19:10

heemayl