Search code examples
rubyregexmarkuptextile

How can I gsub everything until the next empty line?


Given this string:

bc.  some text
 more text
 even more

^ above here is the empty line

I want it to be:

<pre>
some text
more text
even more
</pre>

^ above here is the empty line

How can I regex for "starting from bc. until the first empty line"?

So far I got this:

# note that for some reason a direct .gsub! behaves
# differently/fails when using the block, so I use .gsub
textile_markup = textile_markup.gsub(/^bc.  .*^$/m) { |s| "<pre>#{s[5..(s.length)]}</pre>" }

Understandibly, this matches greedy until the very last empty line - instead of the first one. How can I make the ^$ part non-greedy?


Solution

  • str = 
    "bc.  some text
    more text
    even more
    
    ^ above here is the empty line
    
    bc.  some text
    more text
    even more
    
    ^ above here is the empty line"
    
    puts str.gsub(/^bc\.  (.*?)\n\n/m, "<pre>\n\\1\n</pre>\n\n")
    

    Output:

    <pre>
    some text
    more text
    even more
    </pre>
    
    ^ above here is the empty line
    
    <pre>
    some text
    more text
    even more
    </pre>
    
    ^ above here is the empty line
    

    Explanation

    ? in .*? makes the star operator non greedy

    /m modifier in the end makes dot match newlines