4

I have a code like this:

<pre><code>Some <a href="">HTML</a> code</code></pre>

I need to escape the HTML between the <pre><code></code></pre> tags. I have lots of tags, so I thought - why not let regex do it for me. The problem is I don't know how. I've seen lots of examples using Google and Stackoverflow, but nothing I could use. Can someone here help me?

Example:

<pre><code>Some <a href="http">HTML</a> code</code></pre>

To

<pre><code>Some &lt;a href=&quot;http&quot;&gt;HTML&lt;/a&gt; code</code></pre>

Or just a regex so I can replace anything between the <pre><code> and </code></pre> tags one by one. I'm almost certain that this can be done.

2
  • 4
    If you have multiple levels of nested tags, I don't believe regex can do this for you. HTML is not a regular language. Commented Jul 26, 2013 at 23:35
  • Can you give an example of the result you want? Commented Jul 26, 2013 at 23:45

2 Answers 2

3

This regex will match the parts of the anchor tag you need to put back:

<pre><code>([^<]*?)<a href="(.*?)">(.*?)</a>(.*?)</code></pre>

See a live demo, which shows it matching correctly and also shows the various parts being captured as groups which we'll refer to in the replacement string (see below).

Use the regex above with the following replacement:

<pre><code>\1&lt;a href=&quot;\2&quot;&gt;\3&lt;/a&gt;\4</pre></code>

The \1, \2 etc are the captured groups in the regex that put back what we're keeping from the match.

Sign up to request clarification or add additional context in comments.

Comments

1

A regular expression to return "the thing between <pre><code> and </code></pre>" could be

/(?<=<pre><code>).*?(?=<\/code><\/pre>)/

This uses lookaround expressions to delimit the "thing that gets matched". Typically using regex in situations with nested tags is fraught with danger and you are much better off using "real tools" made specifically for the job of parsing xml, html etc. I am a huge fan of Beautiful Soup (Python) myself. Not familiar with Notepad++, so not sure if its dialect of regex matches this expression exactly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.