views:

89

answers:

4

I have this regex thanks to another wonderful StackOverflow user

/(?:-\d+)*/g

I want it to match things like

133-134-454-58819860
12-13-876-1234346

each block (numbers between -'s) could be any length but it will defiantly only be numbers and there will only 4 blocks.

But currently it's matching things like -2008

I'm really bad at regex and I'm struggling, please help. I'm in JavaScript if that's helpful.

+2  A: 

Try this

/(?:\d+-){3}\d+/

Anton Hansson
Ah that's how you do it. Thanks!
Ben Shelock
+1  A: 

If you want to match exactly four hyphen-separated numeric strings, you would want this:

/^\d+-\d+-\d+-\d+$/

The ^ and $ are anchors to constrain the match to the very beginning and very end of the string. You'll want to remove those if you are looking in a string with other text (e.g. "blah blah 12-12-12-12 blah blah").

bobbymcr
+2  A: 
/(?:-\d+)*/g

breaks down into:

/    about to begin a regex

(    the following is a group

?:   but don't bother storing what this group finds as its own result

-    it must have a dash

\d   followed by digit(s)...

+    at least one digit, perhaps more

)    Im done with the group

*    But get me as many groups like that as you could

/    done with the regex

So it will find all groups like this -0000 but not like this -000-000

While writing this, other faster users published their own regexs. But Im still posting so you follow the logic.

SamGoody
Great little tutorial. Regex is never explained like that. I don't know why. It's so much simpler
Ben Shelock
A: 

As far as checking the number of matches, the following should work:

alert(
  "133-134-454-58819860".match(/^(\d+-){3}\d+$/g).join("\n")
 );

The match function of JavaScript strings takes a regular expression object as a parameter. It returns an array of matches, in the order in which they were found within the string.

David Andres