简体   繁体   中英

Regex match after delimiter and find higher number of the match?

I have a match equation

 function start() { var str = "10x2+10x+10y100-20y30"; var match = str.match(/([az])=?(\\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> 

i need match the power values and also getting out with higher power value only.

example : 10x2+10y90+9x91 out --> "90" . what wrong with my and corret my regex match with suitable format.Thank You

The variable match contains all the powers that matches your regex, not just one. You'll have to iterate over them to find the greatest.

I took your code and modified it a bit to work :

 function start() { var str = "10x2+10x+10y100-20y30"; var match = str.match(/([az])=?(\\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> 

Try this:

 const str = '10x2+10x+10y100-20y30' ,regex = /([az])=?(\\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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM