Как сопоставить строку между двумя словами и повторить этот шаблон для всех двух определенных слов в строке, регулярное выражение?

#javascript #html #regex #mathml

Вопрос:

Поэтому я хочу извлечь MathML из HTML. Например, у меня есть эта строка:

<p>Task:amp;nbsp;</p><math xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mi>x</mi><mo> </mo><mn>2</mn><mo>=</mo><mn>5</mn></mrow></math><p>amp;nbsp;findamp;nbsp;</p><math xmlns="http://www.w3.org/1998/Math/MathML"><msup><mi>x</mi><mn>2</mn></msup></math><p>.</p>

Я хочу соответствовать
<math xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mi>x</mi><mo> </mo><mn>2</mn><mo>=</mo><mn>5</mn></mrow></math> и <math xmlns="http://www.w3.org/1998/Math/MathML"><msup><mi>x</mi><mn>2</mn></msup></math>

Как я могу этого достичь? Я пробовал это выражение /(<math)(.*)(math>)/g , но оно совпадает со всем, что находится между первым <math и последним math> словами.

Ответ №1:

По умолчанию кванторы имеют greedy природу, вам просто нужно сделать это lazy , поместив ? после *

 const str = `<p>Task:amp;nbsp;</p><math xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mi>x</mi><mo> </mo><mn>2</mn><mo>=</mo><mn>5</mn></mrow></math><p>amp;nbsp;findamp;nbsp;</p><math xmlns="http://www.w3.org/1998/Math/MathML"><msup><mi>x</mi><mn>2</mn></msup></math><p>.</p>`;

const regex = /(<math)(.*?)(math>)/g;

const result = str.match(regex);

console.log(result.length);
console.log(result);