GibboK GibboK - 5 months ago 12
Javascript Question

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

At the moment I am using

\b\d-\d\b
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:

1-1
2-22
03-03
4-44
555-555


and so on.

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

Answer

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:

\b\d+-\d+\b

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);