1

I'm trying to come up with some regex to match against 1 hyphen per any number of digit groups. No characters ([a-z][A-Z]).

123-356-129811231235123-1235612346123451235

/[^\d-]/g

The one above will match the string below, but it will let the following go through:

1223--1235---123123-------

I was looking at the following post How to match hyphens with Regular Expression? for an answer, but I didn't find anything close.

@Konrad Rudolph gave a good example.

Regular expression to match 7-12 digits; may contain space or hyphen

This tool is useful for me http://www.gskinner.com/RegExr/

Mat
  • 202,337
  • 40
  • 393
  • 406
Vyache
  • 381
  • 4
  • 15

2 Answers2

3

Assuming it can't ever start with a hyphen:

^\d(-\d|\d)*$

broken down:

^             # match beginning of line
   \d         # match single digit
   (-\d|\d)+  # match hyphen & digit or just a digit (0 or more times)
$             # match end of line

That makes every hyphen have to have a digit immediately following it. Keep in mind though, that the following are examples of legal patterns:

213-123-12314-234234
1-2-3-4-5-6-7
12234234234

gskinner example

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

Alternatively:

^(\d+-)+(\d+)$

So it's one or more group(s) of digits followed by hyphen + final group of digits. Nothing very fancy, but in my tests it matched only when there were hyphen(s) with digits on both sides.

BartekB
  • 8,492
  • 32
  • 33