使用Javascript检测的数字Regex表达式



我对regex完全陌生,因此这个问题很长。我想了解正则表达式代码,以检测html段落标记中的不同类型的数字

  1. 整数(例如:0、1000、1000、028、-1等)
  2. 浮点数(例如:2.3、2.13、0.18、.18、-1.2等)

或可以组合两者的regex 1&2.--所有整数和浮点数加在一起会很好!我在Stackoverflow中尝试了一些解决方案,但结果总是未定义/为空,否则已经无法检测

  1. 比率(例如:如果可能,整体检测为1:3:4)
  2. 分数(例如:0/485、1/1006、2b/3等)
  3. 百分比(例如:15.5%、(15.5%)、15%、0.9%、.9%)

此外,想知道regex是否可以一起检测符号和数字(15.5%,1:3:4),或者在执行数字检测之前必须将它们拆分为不同的部分(例如:15.5+%,1+:+3+:+4)?

这些不同的表达式将被写入Javascript代码中,作为以后不同情况的例外。这些表达式计划像regex一样使用,在下面的附加Javascript片段中检测基本整数:

var paragraphText = document.getElementById("detect").innerHTML;
var allNumbers = paragraphText.match( /d+/g ) + '';
var numbersArray = allNumbers.split(',');
for (i = 0; i < numbersArray.length; i++) { 
//console.log(numbersArray[i]);
numbersArray[i] = "<span>" + numbersArray[i] + "</span>";
console.log(numbersArray[i]);
}

});

非常感谢你的帮助!

以下是简单的实现:

'2,13.00'.match(/[.,d]+/g) // 1 & 2
'1:3:4'.match(/[:d]+/g) // 3
'0/485'.match(/[/d]+/g) // 4
'15.5%'.match(/[.%d]+/g) // 5

您可以使用for语句循环遍历它们,并检查是否检测到一个并中断,或者以其他方式继续。

For decimals numbers: 
->  ((?:d+|)(?:.|)(?:d+))
For percentage numbers : It is the same as decimal numbers followed by % symbol 
->  ((?:d+|)(?:.|)(?:d+))%
For whole numbers: the following regex would work and would exclude any decimal numbers as well, returning you just the integers
->  (^|[^d.])bd+b(?!.d)
For the ration requirement, I have created a complicated one, but you would get the entire ratio as a whole.
-> (((?:d+|)(?:.|)(?:d+)):)*((?:d+|)(?:.|)(?:d+))

最新更新