ilPas
ilPas

Reputation: 21

How to write a regular expression in no particular order?

I have to do a javascript check on a string. The string must have 6 letters and 2 numbers but not necessarily in that order, also 2 numbers and 6 letters.

At the time i have:

/^[A-Za-z]{6,}[0-9]{2,}$/;

Thanks a lot!

Upvotes: 2

Views: 885

Answers (5)

Luigi De Rosa
Luigi De Rosa

Reputation: 720

/^([a-z]{6}|[0-9]{2})([a-z]{6}|[0-9]{2})$/i

You can try here: http://rubular.com/r/pmYxoX6qwD

Upvotes: -1

Denys Séguret
Denys Séguret

Reputation: 382102

Assuming your question is how to check for a mixed set of letters and digits with at least 2 digits and 6 letters, I personally would do it like this :

var str = "abc12def";
var digits = str.match(/\d/g).length;
var ok = /^[A-Za-z0-9]{8,}$/.test(str)
         && digits >=2 && str.length-digits>=6;

Upvotes: 1

Amit
Amit

Reputation: 2565

Here is the answer what I think, took some time for me to post.

/^[a-zA-Z]{6}[\d]{2}|[\d]{2}[a-zA-Z]{6}$

Cheers!!!

Upvotes: 0

Federico Ginosa
Federico Ginosa

Reputation: 316

^(?=(.*[0-9]){2})(?=(.*[A-Za-z]){6})[A-Za-z0-9]{8}$

Upvotes: 6

Joseph Silber
Joseph Silber

Reputation: 219920

Use a | pipe to give your regex two alternatives:

/^[a-z]{6}\d\d$|^\d\d[a-z]{6}$/i

Upvotes: 1

Related Questions