20

My reg ex skills are almost zero and I am trying to match a field to have exactly 7 or 9 numbers (not between 7 or 9 so no 8 numbers is not valid).

I have tried (don't laugh)

/^([0-9]{7} | [0-9]{9})

and

/^([0-9]{7 | 9})

if someone could help and explain the answer that would be much appreciated.

I assume (maybe incorrectly) that is does not matter what (programming) language I am using

Thanks

6 Answers6

26
/^\d{7}(?:\d{2})?$/

\d is modern regex shorthand for [0-9], using (?: prevents a group capture you don't want or need from happening.

Andrei Bârsan
  • 3,473
  • 2
  • 22
  • 46
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 1
    old answer, I know, but why wouldn't this work? `/^\d{7}(\d{2})?$/` I understand it would create a group capture - but does that matter in this instance? I wonder if the reason is memory related? Be gentle - regex is not my forté. – calipoop Mar 28 '18 at 18:10
  • 1
    @calipoop: it will work fine, it's just a poor habit to request behavior (group capture) that you don't need. – chaos Apr 10 '18 at 17:37
  • This answer would not catch 7 zeros like 0000000 – Sani Yusuf Jul 23 '18 at 20:14
  • @SaniYusuf: Of course it does. Maybe try it first. Why did you think that? – chaos Jul 25 '18 at 20:03
  • I should have clarified. It won't catch on an input where type is number since 00000 still evaluates as 0. Changing to type text solved it. – Sani Yusuf Jul 26 '18 at 01:11
10

Your first approach works. Just leave out the blanks, add a $ to match the string end and the trailing slash delimiter. You also could replace [0-9] with the shortcut \d:

/^(\d{7}|\d{9})$/
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
6

Seven or nine digits is seven digits optionally followed by two more digits:

[0-9]{7}([0-9]{2})?
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
3

use this regex ^\d{7}(\d{2})?$

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
0

This is probably easier done in the programming lanuage that you're using, but it can be achieved in regex as well. Take a look at this link : Regular expression to limit number of characters to 10

Community
  • 1
  • 1
mlishn
  • 1,689
  • 14
  • 19
0

Your first one will work if you just remove the spaces (and optionnaly the parenthesis).

kgautron
  • 7,915
  • 9
  • 39
  • 60