2016-08-24 15 views
0

我有一個匹配方程正則表達式在分隔符後匹配並找到更高的匹配數?

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"。 我的錯誤和糾正我的正則表達式匹配與合適的格式。謝謝

回答

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>

+0

在我上面的代碼中更高的功率值'100'.but你r編碼出來是'30' – prasad

+0

@prasad對不起,我忘了在'var line currentValue = parseInt(match [i] .substring(1))'''上使用parseInt();''。它已經被糾正了,現在起作用了。 –

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)

+0

你能解釋一下嗎? – prasad