使用 RegExp 匹配嵌套 [quote]
我正在尝试让正则表达式匹配一些嵌套标签。 (是的,我知道我应该使用解析器,但我的输入是正确的)。
示例:
Text.
More text.
[quote]
First quote
[quote]
Nested second quote.
[/quote]
[/quote]
假设我希望正则表达式将标签简单地更改为
:
Text.
More text.
<blockquote>
First quote
<blockquote>
Nested second quote.
</blockquote>
</blockquote>
我该如何做到这一点,同时匹配开始和结束标签?
I'm trying to get regexp to match some nested tags. (Yes I know I should use a parser, but my input will be correct).
Example:
Text.
More text.
[quote]
First quote
[quote]
Nested second quote.
[/quote]
[/quote]
Let's say I want the regexp to simply change the tags to <blockquote>
:
Text.
More text.
<blockquote>
First quote
<blockquote>
Nested second quote.
</blockquote>
</blockquote>
How would I do this, matching both opening and closing tags at the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不介意正确性,那么您可以使用简单的字符串替换并分别替换每个标签。下面是一些使用 PHP 的
str_replace
替换开始和结束标记的示例:正则表达式的帮助(又是 PHP):
这里
\[(/?)quote]
的匹配被<$1blockquote>
替换,其中$1< /code> 替换为模式第一组的匹配项(
(/?)
,/
或空)。但您确实应该使用一个解析器来跟踪开始和结束标记。否则,您的开始或结束标记可能没有对应的标记,或者(如果您使用更多标记)未正确嵌套。
If you don’t mind correctness, then you could use a simple string replacement and replace each tag separately. Here’s some example using PHP’s
str_replace
to replace the opening and closing tags:Or with the help of a regular expression (PHP again):
Here the matches of
\[(/?)quote]
are replaced with<$1blockquote>
where$1
is replaced with the match of the first group of the pattern ((/?)
, either/
or empty).But you should really use a parser that keeps track of the opening and closing tags. Otherwise you can have an opening or closing tag that doesn’t have a counterpart or (if you’re using further tags) that is not nested properly.
您无法将(任意)嵌套内容与正则表达式匹配。
但是您可以将
[quote]
的每个实例替换为You can't match (arbitrarily) nested stuff with regular expressions.
But you can replace every instance of
[quote]
with<blockquote>
and[/quote]
with</blockquote>
.这是一个糟糕的想法,但您显然试图匹配类似以下内容:
\[\(/?\)quote\]
并将其替换为:<\1blockquote>
It's a lousy idea, but you're apparently trying to match something like:
\[\(/?\)quote\]
and replace it with:<\1blockquote>
您可以使用 2 个表达式。
You could use 2 expressions.