2

I know that with JS RegExp I can match:

  • Exact length; /^[a-zA-Z]{7}$/
  • A length range; /^[a-zA-Z]{3,7}$/
  • A minimum length; /^[a-zA-Z]{3,}$/

What if I wanna match varying specific lengths? Something like: /^[a-zA-Z]{2|4|6}$/ meaning that the string must have either length of 2, 4 or 6 characters. Can I do it using JavaScript's RegExp?

I tried googling but couldn't find a way to search for this specific case, I always end up finding how to match length ranges.

Scenario: I currently have this if statement that I would like to make shorter:

if(typeof ean !== 'string' || !/^\d+$/.test(ean) || [8, 12, 13, 14].indexOf(ean.length) === -1) {
    return false;
}
3
  • Not sure if this helps stackoverflow.com/questions/12784338/… Commented Aug 21, 2014 at 22:29
  • 1
    No, regex won't let you match using a list like that. You could use ^[a-zA-Z]{2}(?:[a-zA-Z]{2}(?:[a-zA-Z]{2})?)?$ instead of an alternation. Commented Aug 21, 2014 at 23:24
  • 1
    If you're really trying to match lengths 2, 4, and 6, you could get clever and do /^(?:[a-zA-Z]{2}){1,3}$/. But this isn't a good, clean solution; it's a clever one. Commented Aug 21, 2014 at 23:49

1 Answer 1

3

All you need is the Regex OR | pattern, but it will require some repetition:

/^(?:[a-zA-Z]{2}|[a-zA-Z]{4}|[a-zA-Z]{6})$/

Note that the (?:...) part is just a non-capturing group, which is used to make all of the alternatives "act as one." Without it, the ^ and $ would have to be included in each alternative.

In your specific case, perhaps try:

/^(?:\d{8}|\d{12,14})$/
Sign up to request clarification or add additional context in comments.

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.