Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7078937
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:36:33+00:00 2026-05-28T06:36:33+00:00

Given a textarea, similar to StackOverflow, I’d like to wrap code (indented by 4

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:36:34+00:00Added an answer on May 28, 2026 at 6:36 am

    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 &lt;, 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 gsub block 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 –

    (^\s*$\n|\A)                                # Capt grp 1, block is preceeded by a blank line or begin of string
    (                                           # Begin "Capture group 2", start of pre/code block
       ^(?:[ ]{4}|\t) .* [^\s] .* $ \n?            # First line of code block (note - lines must contain at least 1 non-whitespace character)
       (?:                                         # Start "Optionally, get more lines of code"
           (?: ^ \s* $ \n? )*                         # Many optional blank lines
           ^(?:[ ]{4}|\t) .* [^\s] .* $ \n?           # Another line of code 
       )*                                          # End "Optionally, get more lines of code", do 0 or more times
    )                                           # End "Capture group 2", end of pre/code block
    

    Ruby code –

    
    regex = /(^\s*$\n|\A)(^(?:[ ]{4}|\t).*[^\s].*$\n?(?:(?:^\s*$\n?)*^(?:[ ]{4}|\t).*[^\s].*$\n?)*)/;
    
    data = '
    Hello Worldsasdasdffasdfasdf  asdf
    
        thisdqweee
    
        asdfasdfasdfasdf
    sdfg
    
        #YYYY {
        height: 100%;
        min-height: 800px;
        margin-right: 20px;
        position: relative;
        }
    
    
        #ZZZZZZ {
        height: 100%;
        overflow: hidden;
        }';
    
    
    # ---
    result = data.gsub(regex) {
       ||
       x=$2;
         ## Construct the return value '\1<pre&gt<code&gt\2</code&gt</pre&gt'.
         ## But, trim each line with 1 to 4 leading spaces (or a tab with regex on the bottom).
         ## They are not necessary now, they are replaced with a code block.
    
       $1 + '<pre&gt<code&gt' +   x.gsub(/^[ ]{1,4}/, '') + '</code&gt</pre&gt'
    };
    
    # Note - Tabs can be trimed too, use : x.gsub(/^(?:[ ]{1,4}|\t)/,'') in the above
    
    print result;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to give default value to a textarea. The code is something like
Given the following text in a textarea: Line 1 stuff.. Line 1 stuff.. Line
Given a <textarea> with a fixed width , I would like its active width
Given the following form: <form id=form name=form> <input name=name/> <input name=version/> <input name=template/> <textarea
Given the following PHP code using DOMDocument : $inputs = $xpath->query('//input | //select |
given the simple code: <textarea>hello</textarea> shouldn't a text area with the word hello be
Given a specific DateTime value, how do I display relative time, like: 2 hours
Given an absolute or relative path (in a Unix-like system), I would like to
Given 2 rgb colors and a rectangular area, I'd like to generate a basic
Given the URL (single line): http://test.example.com/dir/subdir/file.html How can I extract the following parts using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.