Given a textarea, similar to StackOverflow, I’d like to wrap code (indented by 4 spaces) with a pre/code block. I’m trying to use the following regex to find the code:
re = / # Match a MARKDOWN CODE section.
(\r?\n) # $1: CODE must be preceded by blank line
( # $2: CODE contents
(?: # Group for multiple lines of code.
(?:\r?\n)+ # Each line preceded by a newline,
(?:[ ]{4}|\t).* # and begins with four spaces or tab.
)+ # One or more CODE lines
\r?\n # CODE folowed by blank line.
) # End $2: CODE contents
(?=\r?\n) # CODE folowed by blank line.
/x
result = subject.gsub(re, '\1<pre>\2</pre>')
But this isn’t working, here’s the example in Rubular:
http://rubular.com/r/l5faSjR8ya
Any suggestions on how to have this Regex, match the code allow me to wrap a pre/code tags around the code? Thanks
I think there is an escape out of the code mode with any trailing newline not followed by tab or 4 spaces. Not sure but successive newlines would not be included in the code block.
I don’t get Ruby’s regex options too well, but this seems to work: http://rubular.com/r/BlbreoO3sn
((?:^(?:[ ]{4}|\t).*$(?:\r?\n|\z))+)Theorhetically, its in multi-line mode.Just make the replacement
<pre>\1</pre>EDIT
@Rachela Meadows – After further examination, this is a fairly difficult regex.
I managed to exactly duplicate the functionality of the
<pre><code>block features of the online editor here on SO.After obtaining each block and before wrapping in a
<pre><code>, all markup entities should be converted (ie; like<to<, etc). That being said, I didn’t do that step in the Ruby code sample below. I do have the regex’s to do that though.A special note about trimming: The main regex below does not include residual trailing newlines. Nor does the SO functionality. So the code block is correct top to bottom.
However, the leading 4 spaces (or tab) that could be contained in the body can’t be trimmed (and they should be) in the main regex. For that it needs a callback.
Playing around with the
gsubblock mode, its easy to trim those leading spaces/tab.Let me know if you have any problems with this.
Links –
Rubular (for the regex): http://rubular.com/r/pp9oRLQ0xo
Ideone (for the working Ruby code): http://ideone.com/aA9it
Regex compressed –
(^\s*$\n|\A)(^(?:[ ]{4}|\t).*[^\s].*$\n?(?:(?:^\s*$\n?)*^(?:[ ]{4}|\t).*[^\s].*$\n?)*)Regex expanded –
Ruby code –