简体   繁体   English

如何替换正则表达式的最后一个匹配项?

[英]How to replace the last match of regex?

const spaceRegex = /<mspace\s+.*?\/>/
const answer = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace linebreak="newline"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'

I have a regex to match <mspace .... /> , there are two matches in the above answer.我有一个正则表达式来匹配<mspace .... /> ,上面的答案中有两个匹配项。 I want to replace the last match with <mspace width="10px"/>我想用<mspace width="10px"/>替换最后一场比赛

So I want the output to be,所以我希望输出是,

'<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace width="10px"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'

Regex is not a right way to deal with XML.正则表达式不是处理 XML 的正确方法。
The better one is using DOMParser and XMLSerializer so you can traverse the DOM and update elements using DOM methods:更好的方法是使用DOMParserXMLSerializer,这样您就可以使用 DOM 方法遍历 DOM 并更新元素:

 const answer = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace linebreak="newline"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'; const D = (new DOMParser()).parseFromString(answer, "text/xml") const mspaces = D.getElementsByTagName('mspace'); mspaces[mspaces.length-1].outerHTML = '<mspace width="10px"/>'; const updated = (new XMLSerializer()).serializeToString(D); console.log(updated)
 .as-console-wrapper {top:0; max-height:none !important}

The regex solution is also available, but less reliable: regex 解决方案也可用,但不太可靠:

 const answer = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>h</mi><mfenced><mi>x<mspace linebreak="newline"/></mi></mfenced><mo>=</mo><semantics><mrow><mo>-</mo><mn>3</mn></mrow></semantics><mspace linebreak="newline"/><mi>D</mi><mo>=</mo><mi mathvariant="normal">&#x211D;</mi></math>'; const updated = answer.replace(/(.*)<mspace[^/]+\\/>/, '$1<mspace width="10px"/>'); console.log(updated)
 .as-console-wrapper {top:0; max-height:none !important}

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM