GibboK GibboK - 8 months ago 23
Javascript Question

regular expression detect any number of digits separated by only an hyphen

At the moment I am using

with no success.

I would like to use an regular expression which is valid in the following cases:

Any number of digits (at least one numeric value) separated by only a hyphen.

Regular expression is valid in this cases:


and so on.

Could you please tell me what I'm doing wrong and point me out a good example?


Any number of digits (but at least one) would be \d+, where the + says to match the preceding part one or more times (equivalent to \d{1,}). So:


For a list of the regex features that JavaScript supports, check out MDN's regular expressions page

UPDATE: In a comment the OP mentioned trying to match against a string "1-25656{{}". To actually extract the number part from a longer string, use the .match() method:

var matches = inputString.match(/\b\d+-\d+\b/);

...which will return null if there is no match, otherwise will return an array containing the first match. To get all matches add the g (global) flag:

var matches = inputString.match(/\b\d+-\d+\b/g);