【问题标题】:regex include all until closed html tag正则表达式包括所有直到关闭的 html 标记
【发布时间】:2020-11-07 18:11:08
【问题描述】:

例如我有这个内容:

<p>first line</p>
<p>&nbsp;</p>
<ifelse id="df950c19-e3f6-4e14-872b-d73a78e17f8e" typ="ifelse" value="">
<p>Example text</p>
<p><var-input id="80585bab-49a4-4841-b87c-1e004c1a31d1" typ="textzeile" value="" class="mceNonEditable">Textzeile</var-input> ...</p>
</ifelse>
<p>Another ifelse tag</p>
<ifelse id="1199fc18-1f12-4483-b81c-94c8945e6390" typ="ifelse" value="">
<p>This is an <strong>example</strong></p>
</ifelse>
<p>&nbsp;</p>

我在获取打开和关闭 ifelse 标记之间的内容时遇到问题,因为该内容可以包含任何字符,也可以包含换行符等。目前,如果我只有&lt;ifelse ..&gt;...&lt;/ifelse&gt; 的一个元素,则此正则表达式效果很好:

<ifelse id="(?<id>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})" typ="(?:.*)" value="(?:.*)">(?<content>[\s\S\w\W\d\D]*)<\/ifelse>

但如果有两个或更多 ifelse 元素,正则表达式匹配第一个打开标签和最后一个关闭标签之间的全部内容。

我该如何解决这个问题?

最后我想在 JavaScript 和 Python 中使用正则表达式。

【问题讨论】:

  • 搜索“非贪婪正则表达式”
  • &lt;ifelse.*?&lt;/ifelse&gt; 怎么样?
  • 不匹配换行符(终止符)。

标签: javascript python regex


【解决方案1】:

使用惰性运算符? 选择最小的匹配项,然后使用g 标志执行全局搜索:

const content = `
<p>first line</p>
<p>&nbsp;</p>
<ifelse id="df950c19-e3f6-4e14-872b-d73a78e17f8e" typ="ifelse" value="">
<p>Example text</p>
<p><var-input id="80585bab-49a4-4841-b87c-1e004c1a31d1" typ="textzeile" value="" class="mceNonEditable">Textzeile</var-input> ...</p>
</ifelse>
<p>Another ifelse tag</p>
<ifelse id="1199fc18-1f12-4483-b81c-94c8945e6390" typ="ifelse" value="">
<p>This is an <strong>example</strong></p>
</ifelse>
<p>&nbsp;</p>
`;

// * -> *?, using global flag
const regex = /<ifelse id="(?<id>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})" typ="(?:.*)" value="(?:.*)">(?<content>[\s\S\w\W\d\D]*?)<\/ifelse>/g;
console.log(content.match(regex));

对于 Python 使用 re.findall,您可以在 repl.it 上查看此示例。

【讨论】:

    猜你喜欢
    • 2012-04-08
    • 2011-01-24
    • 2011-04-01
    • 2011-04-20
    • 1970-01-01
    • 2015-07-19
    • 2014-01-29
    • 1970-01-01
    相关资源
    最近更新 更多