2016-08-24 2 views
0

У меня есть уравнение MATCHRegex матч после разделителя и найти более высокий номер матча?

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'. но вы r code out is '30' – prasad

+0

@prasad Извините, я забыл использовать' parseInt(); 'on line' var currentValue = parseInt (match [i] .substring (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)

+0

вы не можете объяснить? – prasad

Смежные вопросы