简体   繁体   English

正则表达式可检测由连字符分隔的任意数量的数字

[英]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. 目前,我正在使用\\b\\d-\\d\\b ,但没有成功。

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. 注意:我需要从正则表达式返回true或false。

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,} ). 任何数量的数字(但至少一个数字)将是\\d+ ,其中+表示与前面的部分匹配一次或多次(相当于\\d{1,} )。 So: 所以:

\b\d+-\d+\b

For a list of the regex features that JavaScript supports, check out MDN's regular expressions page 有关JavaScript支持的正则表达式功能的列表,请查看MDN的正则表达式页面

Update: In a comment the OP mentioned trying to match against a string "1-25656{{}" . 更新: OP在一条评论中提到试图与字符串"1-25656{{}"匹配。 To actually extract the number part from a longer string, use the .match() method : 要从更长的字符串中实际提取数字部分,请使用.match()方法

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. ...如果没有匹配项将返回null ,否则将返回包含第一个匹配项的数组。 To get all matches add the g (global) flag: 要获取所有匹配项,请添加g (全局)标志:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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