5

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?

3
  • 2
    Use start and end anchors, and have your 2 patterns separated by |. regex101.com/r/uV8gI4/1#javascript Commented Sep 4, 2016 at 15:00
  • 1
    @squint no need for anchors in pattern regexps. Commented Sep 4, 2016 at 15:25
  • @torazaburo: Yes, you're right. Good point! Commented Sep 4, 2016 at 17:05

3 Answers 3

2

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

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

RegEx Demo

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much. This one well solved my problem!
@torazaburo: \b is used for word boundary in this regex.
My question was semi-rhetorical. There is no need for word boundaries. The regexp in the pattern attribute is matched against the entire input.
Word boundaries are needed otherwise it will match D-DDDD in DDD-DDDD
no, because as I said, values of the pattern attribute have implicit anchors.
0

Another simple alternation example:

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

1 Comment

Yes, but the anchors are not necessary.
0

It might be slightly shorter to write

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.