如何解决如何在两个单词之间匹配字符串,并为字符串 Regex 中的所有两个定义的单词重复此模式?
所以我想从 HTML 中提取 MathML。例如,我有这个字符串:
<p>Task: </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> find </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: </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> find </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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。