0

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?

Notes: I need to return true or false from the regex.

GibboK
  • 71,848
  • 143
  • 435
  • 658

1 Answers1

1

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

Final update: If you want to test whether a string contains nothing but two numbers separated by a hyphen use this expression:

^\d+-\d+$

var isValid = /^\d+-\d+$/.test(inputString);
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • could you please double check here https://regex101.com/r/bN8lS9/1 if I am adding 1-25656{{} does not work – GibboK Jul 02 '16 at 07:15
  • 2
    But...the regex at that link *did* match the `1-25656` part of the string. In JS, if you say `"1-25656{{}".match(/\b\d+-\d+\b/)` you'll get back `["1-25656"]`. If you want to match all such numbers in a longer string, add the `g` flag, so `yourString.match(/\b\d+-\d+\b/g)`. – nnnnnn Jul 02 '16 at 07:16
  • Please look at this example, I need to return false for isValid at the moment it return true. var data = '1-50{}'; var isValid = /\b\d+-\d+\b/g.test(data); – GibboK Jul 02 '16 at 07:50
  • Never use `RegExp.test` with a global modifier `/g`. – Wiktor Stribiżew Jul 02 '16 at 07:52
  • could you please provide me an example for isValid, thanks for your support – GibboK Jul 02 '16 at 07:54
  • 1
    @GibboK: If you **ONLY** want to have numbers and hyphens, apply anchors like in Tushar's comment. – Jan Jul 02 '16 at 07:54
  • @revo: See http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results – Wiktor Stribiżew Jul 02 '16 at 10:31