J-bob
J-bob

Reputation: 9126

How to match a string of length 4 or 6, but not 5?

In javascript regular expressions: /^[0-9]{4}$/ will match a string of digits of length 4. /^[0-9]{4,6}$/ will match a string of digits of length 4,5 or 6. How would I match strings of only length 4 or 6, but not 5? This is just an example of course, the two lengths could be anything. What if I wanted to match more than just two lengths?

Upvotes: 2

Views: 967

Answers (2)

Dave
Dave

Reputation: 46289

While you could certainly build regular expressions for this, of the form

/^([0-9]{4}|[0-9]{6})$/

Or

/^([0-9]{2}){2,3}$/

(Or like anubhava suggested)

I'd suggest you'd be better off splitting this specific case into two problems: valid characters and length.

(value.length == 4 || value.length == 6) && /^[0-9]*$/.test( value )

This makes it easier to extend to arbitrary numbers of valid lengths, and makes it easy to extend the valid character set. If you have a lot of valid lengths, and you're targeting IE9+, you can use an array:

var validLengths = [4,6,etc];
var validChars = /^[0-9]*$/;
if( validLengths.indexOf( value.length ) !== -1 && validChars.test( value ) )

To target IE8 or below with that method, you could use an object instead or make your own array lookup function (which is easy enough).

You can even apply this splitting logic within the regular expression using lookaheads, but it's not pretty (and is less efficient):

/^(?=[0-9]*$)(.{4}|.{6})$/

Upvotes: 3

anubhava
anubhava

Reputation: 785296

You can use:

/^[0-9]{4}([0-9]{2})?$/

This will match either 4 digits or 6 digits but not 5.

Upvotes: 7

Related Questions