Wednesday, 18 September 2013

Ruby gsub regex doesn't match end of string

Ruby gsub regex doesn't match end of string

I'm trying to add <p> tags to user-generated text in place of line breaks.
Here is my code:
def prep_ug_text string, tags=[]
tags = tags.empty? ? ['p'] : tags
sanitize string.gsub(/(.*)[\n\r\Z$]+/, "<p>\\1</p>"), tags: tags
end
The replacement works exactly as expected for the first paragraph, but it
only wraps the final block of text if I add an extra carriage return. It
seems like the \Z and $ are not matching as I expect them to.
What am I doing wrong?
Examples:
This...
Lorem ipsum dolor sit amet.
Vestibulum laoreet erat id quam.
...turns into this
<p>Lorem ipsum dolor sit amet.</p>
Vestibulum laoreet erat id quam.

No comments:

Post a Comment