我对正则表达式来说是全新的,因此这个问题很长。 我想知道html段落标记中正则表达式表达式代码来检测不同类型的数字。
- 整数(例如:0,1,000,1000,028,-1等)
- 浮动数(例如:2.3,2.13,0.18,.18,-1.2等)
醇>或正则表达式可以组合两者。& 2. - 所有整数和浮点数一起会很好!我在Stackoverflow中尝试了一些解决方案,但结果总是未定义/ null,否则无法检测到
- 比率(例如:如果可能,1:3:4检测整体)
- 小数(例如:0 / 485,1 / 1006,2 / 3等)
- 百分比(例如:15.5%,(15.5%),15%,0.9%,。9%)
醇>
另外,想知道正则表达式是否可以一起检测符号和数字(15.5%,1:3:4),或者在检测到之前必须将它们分成不同的部分可以执行数字(例如:15.5 +%,1 +:+ 3 +:+ 4)?
这些不同的表达式意在写入 Javascript 代码,作为后续案例的不同例外。计划使用表达式,就像在下面附加的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]);
}
});
非常感谢你的帮助!
答案 0 :(得分:0)
以下是简单的实现:
'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
语句循环遍历它们,并检查是否有一个被检测到并中断,或者继续以其他方式继续。
答案 1 :(得分:0)
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.])\b\d+\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+))