仅当内部存在 table 时,正则表达式才会在评论中获取内容
Regex getting content within comments only if a table exists inside
假设我有一些 HTML,其中包含像这样包裹 table 的评论:
<!--product_template -->
<table class='template'>{blah}</table>
<!--end_product_template-->
有时评论中可以包含额外的文本,如下所示:
<!--product_template *THIS IS MORE COMMENT TEXT* -->
<table class='template'>{blah}</table>
<!--end_product_template-->
但是... 用户偶尔可能会错误地创建如下内容:
<!--product_template *THIS IS MORE COMMENT TEXT* -->
<p> </p>
<!--end_product_template-->
我需要能够找到这些评论部分并阅读内容仅在包含table的地方
我有这个简单的正则表达式 <!--product_template.*?<table.*?<!--end_product_template-->
几乎可行:
https://regex101.com/r/PpDj3y/3
但是...正如您从 fiddle 中看到的那样,它正在捕获任何 <!--product_template
和 <!--end_product_template-->
之间的任何 table 但它只需要捕获介于<!--product_template
和第一个 <!--end_product_template-->
随后。
我不知道该怎么做!我的正则表达式匹配 fiddle 在前两个匹配中是正确的,但第三个包含太多信息,应该只在最后一行的开头开始捕获,注释不包含 table 不应该被捕获。
编辑:
不是重复问题?我的问题是仅当两个字符串包含某些其他文本时才询问两个字符串之间的文本,被引用为重复的问题仅与查找两个字符串之间的文本有关,不包括这些字符串还必须包含“
”的特定附加要求
您需要的正则表达式是基于 tempered greedy token:
的正则表达式
<!--product_template(?:(?!<!--product_template).)*?<table.*?<!--end_product_template-->
参见regex demo。
要点是 .*?
从最左边的位置匹配到另一个最左边的位置,但它仍然会根据需要匹配尽可能多的字符以 return 一个有效的匹配。如果前一个块不包含 <table
子字符串,.*?
可能会溢出另一个 <!--product_template
子字符串。脾气暴躁的贪婪令牌将阻止这种情况。
详情:
<!--product_template
- 文字子串
(?:(?!<!--product_template).)*?
- 任何不以 <!--product_template
字符序列开始的字符,尽可能少,直到第一次出现后续子模式。
<table
- 文字子串
.*?
- 任何 0+ 个字符尽可能少直到第一个...
<!--end_product_template-->
- 文字子串
假设我有一些 HTML,其中包含像这样包裹 table 的评论:
<!--product_template -->
<table class='template'>{blah}</table>
<!--end_product_template-->
有时评论中可以包含额外的文本,如下所示:
<!--product_template *THIS IS MORE COMMENT TEXT* -->
<table class='template'>{blah}</table>
<!--end_product_template-->
但是... 用户偶尔可能会错误地创建如下内容:
<!--product_template *THIS IS MORE COMMENT TEXT* -->
<p> </p>
<!--end_product_template-->
我需要能够找到这些评论部分并阅读内容仅在包含table的地方
我有这个简单的正则表达式 <!--product_template.*?<table.*?<!--end_product_template-->
几乎可行:
https://regex101.com/r/PpDj3y/3
但是...正如您从 fiddle 中看到的那样,它正在捕获任何 <!--product_template
和 <!--end_product_template-->
之间的任何 table 但它只需要捕获介于<!--product_template
和第一个 <!--end_product_template-->
随后。
我不知道该怎么做!我的正则表达式匹配 fiddle 在前两个匹配中是正确的,但第三个包含太多信息,应该只在最后一行的开头开始捕获,注释不包含 table 不应该被捕获。
编辑:
不是重复问题?我的问题是仅当两个字符串包含某些其他文本时才询问两个字符串之间的文本,被引用为重复的问题仅与查找两个字符串之间的文本有关,不包括这些字符串还必须包含“
”的特定附加要求您需要的正则表达式是基于 tempered greedy token:
的正则表达式<!--product_template(?:(?!<!--product_template).)*?<table.*?<!--end_product_template-->
参见regex demo。
要点是 .*?
从最左边的位置匹配到另一个最左边的位置,但它仍然会根据需要匹配尽可能多的字符以 return 一个有效的匹配。如果前一个块不包含 <table
子字符串,.*?
可能会溢出另一个 <!--product_template
子字符串。脾气暴躁的贪婪令牌将阻止这种情况。
详情:
<!--product_template
- 文字子串(?:(?!<!--product_template).)*?
- 任何不以<!--product_template
字符序列开始的字符,尽可能少,直到第一次出现后续子模式。<table
- 文字子串.*?
- 任何 0+ 个字符尽可能少直到第一个...<!--end_product_template-->
- 文字子串