1

When I want to test if input string is at least length 10 and at most length 13, I use this pattern: [0-9]{10,13}

But how would you test if the string length is 10 or 13 and nothing in between?

EDIT: I see two dominant solutions:

1) Using length1 OR length2 2) Using length1 + optional characters of (length2 - length1)

Just wondering: are there any performance differences between the two?

Arman Bimatov
  • 1,789
  • 4
  • 24
  • 31
  • Well, it's hard to define a search string for a question like this. – Arman Bimatov Nov 03 '13 at 20:53
  • @still_learning nice finding :) – HamZa Nov 03 '13 at 20:56
  • @ArmanBimatov you might check this [question](http://stackoverflow.com/questions/3470990/is-micro-optimization-worth-the-time/3471356#3471356) out and this [tweet](https://twitter.com/ircmaxell/status/370993140628344833) :) – HamZa Nov 03 '13 at 21:30
  • Not quite the same question. The nominated duplicate asks whether there is another solution. This question asks about the performance difference between two solutions. – Wayne Conrad Mar 22 '14 at 12:26

2 Answers2

2

Another option would be

^[0-9]{10}(?:[0-9]{3})?$

regex101 demo

jkshah
  • 11,387
  • 6
  • 35
  • 45
  • Don't rip off the solution from a duplicate, you have the power to close it as duplicate :) – HamZa Nov 03 '13 at 20:58
  • @HamZa Sorry to say but I didn't even see duplicate post or ans. I was trying to construct my solution. If you believe it's ok, if you not still it's ok. It may just be coincident. the other 4 ans are similar, in-fact same, that doesn't mean they have copied from one another! – jkshah Nov 03 '13 at 21:01
  • I removed my answer since all people overflowed the question with almost the same answer, you've come with one that's not similar and I find it really creative if you found it by your own. But don't forget to "clean up" stackoverflow. Well you're not "forced" anyway, just suggesting ... – HamZa Nov 03 '13 at 21:04
  • @HamZa Had I seen that duplicate, I would surely have removed my ans and posted the ans in comment. Now that nobody else has posted this option, I would like to retain it. I do not intend to flood SO with rep rip-off answers! – jkshah Nov 03 '13 at 21:09
1

use this expression ^((?:\d{3}){3,4}\d)$

bukart
  • 4,906
  • 2
  • 21
  • 40