简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM