首页 > 解决方案 > 如何从正则表达式匹配中删除特定的字符串模式?不能使用 XML 解析器,它只能识别好的 XML 标签

问题描述

我有一个正则表达式模式 /[\w]+=[\w" :]+/ 来删除 xml 标签中的 /id=""/ 之类的属性,我试图使这个模式尽可能通用,但是这个模式删除 /href="https:/ 属性以及我不想从 xml 标记中删除的属性

正则表达式模式 /[\w]+=[\w" :]+/

源 xml 字符串是,

<table id="this is id">
<tr id="this tr id">
<a href="https://www.w3schools.com">Visit W3Schools.com!</a>
<div id="this is div id"><span id="div Class:a">this is span 
text</span></div>
</tr>
</table>

我期待这个o / p,

<table >
<tr >
<a href="https://www.w3schools.com">Visit W3Schools.com!</a>
<div ><span >this is span text</span></div>
</tr>
</table>

但我得到这个o / p,

<table >
<tr >
<a //www.w3schools.com">Visit W3Schools.com!</a>
<div ><span >this is span text</span></div>
</tr>
</table>

以上内容可在此链接中使用My RegEx pattern to remove id attribute

标签: regexregex-negation

解决方案


TL;DR使用否定的前瞻断言

细节

您可以使用否定的前瞻断言开始您的正则表达式,该断言将排除您不想匹配的模式:

(?!href)\b[\w]+=[\w" :]+

如果您要排除两个或多个属性,您可以在它们之间用“或”列出它们:

(?!href|exclude_this_too)\b[\w]+=[\w" :]+

演示,从你的扩展

请注意\b我还添加了:它说[\w]+必须在单词的开头。这很重要,否则它只匹配ref=...遗漏h,这不是你想要的。


推荐阅读