Otto
Otto

Reputation: 59

JS RegEx to match certain patterns only

I need to adapt my Javascript RegEx to match certain patterns only. The RegEx is used in the html5 pattern attribute to validate an input field.

I want to accept alphanumeric pattern of the following types only:

A-AAAA or BB-BBB (the intended pattern is: 1 digit before the "-", and 4 digits after the "-", or 2 digits before the "-", and 3 digits after the "-").

My current RegEx is:

/([\w]{1,2})(-([\w]{3,4}))/g

This one works, but accepts CC-CCCC as well, which is obviously a valid input pattern, but not the intended pattern. It accepts DDD-DDDD as well; valid again, but not intended.

Could you please assist adapting the pattern?

Upvotes: 5

Views: 105

Answers (3)

anubhava
anubhava

Reputation: 784898

You can use alternation based regex in HTML5 pattern attribute (as it has implicit anchors):

/(?:\w-\w{4}|\w{2}-\w{3})/

RegEx Demo

Upvotes: 2

user663031
user663031

Reputation:

It might be slightly shorter to write

/\w(-\w|\w-)\w{3}/

Upvotes: 0

maioman
maioman

Reputation: 18734

Another simple alternation example:

/^\w-\w{4}$|^\w{2}-\w{3}$/

Upvotes: 0

Related Questions