JavaScript正则表达式用于测试数字(整数或小数,正数或负数)范围

huangapple go评论71阅读模式
英文:

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 &lt;&lt; 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 = &#39;-10.5-8&#39;;

var array = str.match(rangeRegex);

if( array !== null &amp;&amp; array[1] &lt; array[2]){
  console.log(&#39;good&#39;);
}
else{
  console.log(&#39;bad&#39;);
}

console.log(array);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月17日 21:00:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定