我有一个匹配方程式
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();
&#13;
<p id="demo"></p>
&#13;
我需要匹配功率值,并且只能获得更高的功率值。
示例:10x2+10y90+9x91 out --> "90"
。
我的错误与我的正则表达式相匹配的格式是合适的。谢谢你
答案 0 :(得分:0)
变量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>
答案 1 :(得分:0)
试试这个:
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)