Konstantin
Konstantin

Reputation: 3123

How to replace the first and the last occurrences in a string

I have a long string which contains several urls coded in BBcode. For example, part of my string:

"...[url=http://example1.com][img]http://picture.com/1.jpg[/img][/url]
[url=http://example2.com][img]http://picture.com/2.jpg[/img][/url]
[url=http://example3.com][img]http://picture.com/3.jpg[/img][/url]..."

contains lines before and after "...", but no more lines containing "[url=" and "[/url]". I want to replace the first occurrence of "[url=" with "[spoiler][url=]" and the last occurrence of "[/url]" with "[/url][/spoiler]" to obtain this:

"...[spoiler][url=http://example1.com][img]http://picture.com/1.jpg[/img][/url]
[url=http://example2.com][img]http://picture.com/2.jpg[/img][/url]
[url=http://example3.com][img]http://picture.com/3.jpg[/img][/url][/spoiler]..."

How can I achieve this with Ruby?

Upvotes: 0

Views: 137

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can try this:

str = str.sub(/\[url=.+\[\/url\]/m, '[spoiler]\0[/spoiler]') 

the idea is to replace all the code block between the first [url..] and the last [/url] (tags included) with itself adding [spoiler] before and [/spoiler] after in the replacement string.

Since the quantifier + is greedy the substring [/url] must be the last.

Upvotes: 4

Related Questions