Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make regular expression with only 3 characters and 3 digits?

I have tried the below regex for match here http://rubular.com/ but it matches only 3 characters or 3 digits at a time.

^((\d{3})|(\w{3}))$

I need result like this:

123eee

4r43fs

like image 527
TeamA1 Avatar asked May 07 '14 05:05

TeamA1


1 Answers

Here you go:

^(?=(?:[a-z]*\d){3})(?=(?:\d*[a-z]){3})\w{6}$

http://regex101.com/r/hO5jY9

If there are at least three digits, at least three letters, and at most six characters, the string has to match.

How does this work?

  1. This is a classic password-validation-style regex.
  2. The two lookaheads check that we have at least three digits and at least three letters
  3. After these assertions, we are free to match any 6 characters with \w{6} until the end of the string

The lookaheads

Let's break down the first lookahead: (?=(?:[a-z]*\d){3})

It asserts that three times ({3}), at this position in the string, which is the start of the string as asserted by ^, we are able to match any number of letters, followed by a single digit. This mean there must be at least three digits.

like image 167
zx81 Avatar answered Oct 08 '22 00:10

zx81