0

I'm trying to match tracking numbers for some express shipping company. Valid tracking numbers for that company have either 12, 15, 20 or 22 digits. What's a regular expression that matches 12, 15, 20 or 22 digits, but not other lengths?

It is known that quantities can be used in regular expressions with curly brackets indicating that the preceding token must be matched a certain number of times.

So, {12,15} will match 12 to 15 tokens, not only exactly 12 or exactly 15. {12} will match exactly 12. {12,} will match 12 or more. And no, {12|15} isn't valid.

So, while I hoped that something like:

/\D([0-9]{12|15})\D/ (with \D to match a non-digit character)

was valid, my current solution is this:

\D([0-9]{12}|[0-9]{15})\D/

Obviously, my final expression needs to match strings of 20 or 22 digits as well, so this line of thought would result in the lengthy:

/\D([0-9]{12}|[0-9]{15}|[0-9]{20}|[0-9]{22})\D/

where I hoped that something alike:

\D([0-9]{12|15|20|22})\D

would work as well.

(Working pattern, with valid and non-valid numbers, is shared at http://regexr.com/3gfb3.)

Jochem Schulenklopper
  • 6,452
  • 4
  • 44
  • 62
  • 1
    There has been a lot of such questions. Either your way, or optional groups. There is no other way. – Wiktor Stribiżew Jul 31 '17 at 13:22
  • Thanks. I did look for it before asking the question, but couldn't find a duplicate (and it wasn't suggested when I typed my question). – Jochem Schulenklopper Jul 31 '17 at 13:28
  • I think there are other similar posts. I think one of them must be included into [*What does this regex mean* post](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean/22944075). – Wiktor Stribiżew Jul 31 '17 at 13:29
  • 1
    @JochemSchulenklopper The title of your question at the moment isn't a great search term either. Maybe you could adjust it to reflect the search terms you used, so future searchers might find the dupe by your post. – Sebastian Proske Jul 31 '17 at 13:40
  • @SebastianProske, done. I didn't see that before - the title was truncated involuntarily during editing it. – Jochem Schulenklopper Jul 31 '17 at 14:00

0 Answers0