JS RegEx to match specific patterns only

I need to adapt Javascript RegEx to fit specific patterns. RegEx is used in the html5 pattern attribute to validate the input field.

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

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

My current RegEx:

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

This works, but also accepts CC-Priv, which is obviously a valid input pattern but not a targeted pattern. It also accepts DDD-DDDD; valid again but not intended.

Could you help adapt the template?

+5
source share
3 answers

You can use the regex with alternation in the HTML5 pattern attribute of the HTML5 pattern (since it has implicit bindings):

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

RegEx Demo

+2
source

Another simple alternation example:

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

Maybe a little shorter to write

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

All Articles