英文:
Javascript regex to test a number (integer or decimal, positive or negative ) range
问题
我想要确定一个字符串是否是一个有效的范围,以 -
作为分隔符。像这样的示例应该通过测试:
1-5
1-10.1
10.5-20.5
-10.5-8
-2--1 << minus two to minus one
-3.5--1
-20.5--2.1
负数到负数的范围可能看起来有点奇怪,因为没有空格,但我被迫这么做。
你认为这个正则表达式对这个任务是否足够好?
/(-?[0-9]+[.]*)+-(-?[0-9]+[.]*)+/
英文:
I want to find out whether a string is a valid range with -
as a separator. Examples like these should pass the test:
1-5
1-10.1
10.5-20.5
-10.5-8
-2--1 << minus two to minus one
-3.5--1
-20.5--2.1
The negative to negative range may seem weird without spaces but I'm stuck with that.
Do you think this regex is good enough for the job?
/(-?[0-9]+[.]*)+-(-?[0-9]+[.]*)+/
答案1
得分: 1
正则表达式不执行算术运算,因此确保左侧数字小于右侧数字需要额外的处理。
您可以通过使用捕获组来验证输入是否具有正确的格式并提取数字:
^(-?\d*\.?\d+)-(-?\d*\.?\d+)$
^
- 行的开头(
- 开始捕获组-?
- 可选的破折号(负数)\d*\.?\d+
- 允许浮点数或整数
)
- 结束捕获组-
- 范围破折号(
- 开始捕获组-?
- 可选的破折号(负数)\d*\.?\d+
- 允许浮点数或整数
)
- 结束捕获组$
- 行的结尾
但是,要验证第一个数字是否小于第二个数字需要额外的 JavaScript 处理。
var rangeRegex = /^(-?\d*\.?\d+)-(-?\d*\.?\d+)$;
var str = '-10.5-8';
var array = str.match(rangeRegex);
if (array !== null && array[1] < array[2]) {
console.log('good');
} else {
console.log('bad');
}
console.log(array);
https://regex101.com/r/m6cT2o/1
英文:
Regex does not perform arithmetic so making sure the left-side number is less than the right side requires additional processing.
You can verify the input is in the correct format and extract the numbers by making use of capture groups:
^(-?\d*\.?\d+)-(-?\d*\.?\d+)$
^
- start of line(
- start capture group-?
- optional dash (negative)\d*\.?\d+
- allow floating or whole number
)
- end capture group-
- range dash(
- start capture group-?
- optional dash (negative)\d*\.?\d+
- allow floating or whole number
)
- end capture group$
- end of line
https://regex101.com/r/m6cT2o/1
However, to verify that the first number is smaller than the second number requires additional JS processing.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var rangeRegex = /^(-?\d*\.?\d+)-(-?\d*\.?\d+)$/;
var str = '-10.5-8';
var array = str.match(rangeRegex);
if( array !== null && array[1] < array[2]){
console.log('good');
}
else{
console.log('bad');
}
console.log(array);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论