Mike
Mike

Reputation: 24393

Matching exactly 8 digits with 0 or more dashes

I am trying to match an exactly 8 digit phone number that has 0 or more dashes in it. For example, the following should all match:

12345678
123456-78
1234-5678
1-2-3-4-5-6-7-8

If I ignore the dashes, it is rather simple. I can just use:

[\d]{8}

If I want to match a string containing at least 8 characters (digits and dashes) I can use:

[\d-]{8,}

However, here I can't put an upper bound on the number of characters because I don't know how many dashes the number would have.

The only way I thought of would be to use:

[0-9][-]?[0-9][-]?[0-9][-]?[0-9][-]?[0-9][-]?[0-9][-]?[0-9][-]?[0-9]

However, this seems really messy for something that (at least in my mind) seems simple. Is there an easier way to do this?

Upvotes: 3

Views: 3431

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627145

You should use

^[0-9](-?[0-9]){7}$
^([0-9]-?){8}\b$

See the regex demo #1 and regex demo #2, where \b is used to make sure the last char is a digit (that is a word char).

Details

  • ^ - start of string
  • [0-9] to match a digit since \d in various regex flavors may match more than just ASCII digits from 0 to 9.
  • (-?[0-9]){7} - matches 7 sequences of an optional hyphen and a digit, and will not allow trailing hyphen at the end of the string.
  • ([0-9]-?){8} - matches eight occurrences of a digit followed with an optional - char
  • \b$ - is a trick to make sure the last char is of a word type. Since the pattern can only match a - (a non-word char) or a digit at the end, \b automatically makes sure the last char is a digit.

Upvotes: 2

anubhava
anubhava

Reputation: 785691

You can use this regex with optional - after each digit:

^([0-9]-?){8}$

If your regex supports \d then use:

^(\d-?){8}$

RegEx Demo

Upvotes: 5

Related Questions