正则表达式在分隔符后匹配并找到更高的匹配数?
问题描述:
我有一个匹配方程正则表达式在分隔符后匹配并找到更高的匹配数?
function start() {
var str = "10x2+10x+10y100-20y30";
var match = str.match(/([a-z])=?(\d+)/g);//find the higher value of power only and also print the power value only withput alphapets).i need match like "100"
var text;
if(match < 10)
{text = "less 10";}
else if(match == "10")
{text == "equal";}
else
{text ="above 10";}
document.getElementById('demo').innerHTML=text;
}
start();
<p id="demo"></p>
我需要匹配的功率值,也失控,只有更高的功率值。
例如:10x2+10y90+9x91 out --> "90"
。 我的错误和纠正我的正则表达式匹配与合适的格式。谢谢
答
变量match
包含所有匹配您的正则表达式,而不仅仅是一个权力。你必须遍历它们才能找到最好的。
我把你的代码,并修改它一下工作:
function start() {
var str = "10x2+10x+10y100-20y30";
var match = str.match(/([a-z])=?(\d+)/g);//find the higher value of power only and also print the power value only withput alphapets).i need match like "100"
var max = 0;
for (var i = 0; i < match.length; i++) { // Iterate over all matches
var currentValue = parseInt(match[i].substring(1)); // Get the value of that match, without using the first letter
if (currentValue > max) {
max = currentValue; // Update maximum if it is greater than the old one
}
}
document.getElementById('demo').innerHTML=max;
}
start();
<p id="demo"></p>
答
试试这个:
const str = '10x2+10x+10y100-20y30'
,regex = /([a-z])=?(\d+)/g
const matches = []
let match
while ((match = regex.exec(str)) !== null) {
matches.push(match[2])
}
const result = matches.reduce((a, b) => Number(a) > Number(b) ? a : b)
console.log(result)
+0
你能解释一下吗? – prasad
在我上面的代码中更高的功率值'100'.but你r编码出来是'30' – prasad
@prasad对不起,我忘了在'var line currentValue = parseInt(match [i] .substring(1))'''上使用parseInt();''。它已经被纠正了,现在起作用了。 –