0

With ruby gsub(), in string <code>balabala or blank \n another balabala or blank</code>, replacing all \n inside <code>...</code> block into <br>, but do nothing to the content outside <code>...</code>.

I tried /<code>.*(\\n?).*<\/code>/ but not working:

html = '<pre>do \n nothing<code>line \n break</code></pre>'

html = html.gsub(/<code>.*(\\n?).*<\/code>/) { "<br>" }

print html

# actual result: <pre>do \n nothing<br></pre>

# expect result: <pre>do \n nothing<code>line <br> break</code></pre>

0

1 Answer 1

3

Match all substrings between <code> and </code> and replace all \n with <br> in those matches only:

html = html.gsub(/<code>.*?<\/code>/m) { $~[0].gsub('\n', '<br>') }
Sign up to request clarification or add additional context in comments.

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.