0

I'm interested in a concise way to specify different allowable lengths for a string of numbers. I want to allow strings of length 2, 4, 6, 8, and 10, but nothing in between. The following works just fine, but it is a bit long-winded:

var regex = /^([0-9]){2}|([0-9]){4}|([0-9]){6}|([0-9]){8}|([0-9]){10}$/;

Is there a shorter, less brute force way I can do this?

Thanks!

2
  • 1
    You can shorten [0-9] by \d Commented Aug 5, 2014 at 17:50
  • I think the alternations are the longest parts. The answer below (user3218114) looks like the best thing you can do with regex. Otherwise use regex to verify it's all numbers and then use something string.length() and check the value of that Commented Aug 5, 2014 at 17:52

1 Answer 1

3

I want to allow strings of length 2, 4, 6, 8, and 10, but nothing in between

You can try. A shorter version

^([0-9]{2}){1,5}$

DEMO

OR in simple term

^([0-9][0-9]){1,5}$

Enclose the whole regex inside parenthesis (...) for capturing groups.

Regex explanation:

  ^                        the beginning of the string
  (                        group and capture to \1 (between 1 and 5 times):
    [0-9]{2}                 any character of: '0' to '9' (2 times)
  ){1,5}                   end of \1
  $                        the end of the string
Sign up to request clarification or add additional context in comments.

7 Comments

And you can go even further by throwing a \d in: ^((\d{2})){1,5}$ Fantastic lateral thinking here, nice one!
I think your capture groups are in the wrong place, though: ^((?:\d{2}){1,5})$ (one capture group for the whole thing).
@user3218114 Even shorter changing [0-9] by \d and no need to double parenthesis. ^(\d{2}){1,5}$ would work too.
@T.J.Crowder It's just for match to validate not for grouping.
Ah very clever, this achieves exactly what I wanted. Thanks! Also thanks for the regex101.com link. I had no idea that website existed. P.S. I'll accept the answer when stackoverflow lets me.
|

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.