如何在两个单词之间匹配字符串,并为字符串 Regex 中的所有两个定义的单词重复此模式?

问题描述

所以我想从 HTML 中提取 MathML。例如,我有这个字符串:

<p>Task:&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>&nbsp;find&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> 字之间的所有内容

解决方法

默认情况下,量词本质上是 greedy,您只需要将 lazy 放在 ? 之后使其成为 *

const str = `<p>Task:&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>&nbsp;find&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);