简体   繁体   English

JavaScript中的递归正则表达式模式

[英]Recursive regex pattern in JavaScript

I know it's going to be a VERY obvious answer, but I can't find anything on how to do this. 我知道这将是一个非常明显的答案,但我找不到有关如何执行此操作的任何信息。

I'm trying to unescape < and > within an HTML string 我正在尝试对HTML字符串中的<>进行转义

My test output string is essentially: 我的测试输出字符串本质上是:

```php
&gt;h2&lt;Heading2&gt;/h2&lt;
```

`&gt;h2&lt;Heading2&gt;/h2&lt;`

&gt;h2&lt;Heading2&gt;/h2&lt;

So in this example we have Github flavoured Markdown, a regular code markdown snippet, and then raw text all with the same HTML tag. 因此,在此示例中,我们使用了Github风格的Markdown,一个常规的code markdown代码段,然后使用了具有相同HTML标签的原始文本。 I want to unescape the raw tag (the third one) to actually become a link. 我想取消转义原始标签(第三个标签)以实际上成为链接。 The ideal output would be something like this. 理想的输出将是这样的。

```php
&gt;h2&lt;Heading2&gt;/h2&lt;
```

`&gt;h2&lt;Heading2&gt;/h2&lt;`

<h2>Heading2</h2>

I'm getting stuck at getting multiple &gt; 我被困在获取多个&gt; in the same line. 在同一行。

Current regex: 当前正则表达式:

/(?:.*?(&gt;))/

This will get the first entry. 这将获得第一个条目。

/(?:.*?(&gt;))/g

This one gets the second entry. 这个获得第二项。 I want it to be able to get EVERY entry. 我希望它能够获得每个条目。 Then, it's just a matter of throwing the tick pieces. 然后,只需要扔掉刻度线即可。

/(?:```|`)(?:.*?(&gt;)).*?(?:```|`)/gs

If you're intending on using a regular expression for this task, you can consider the following: 如果打算为此任务使用正则表达式,则可以考虑以下几点:

var r = s.replace(/((`(?:``)?)[^`]*\2)|&gt;/g, '$1<')
         .replace(/((`(?:``)?)[^`]*\2)|&lt;/g, '$1>')
         .replace(/`[<>]+/g, '`');

Working Demo 工作演示

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

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