1

Let's say I have a string like so:

"Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator."

I want to find all occurrences of [post]*[/post] and replace it with the title of the post represented by the number. I'd end up with something like so:

"Lorem ipsum de color Angry Turtle sit amet Fuzzy Rabit desectator."

I'm guessing a regex will be needed... looking for what the regex would be and how to use.

tybro0103
  • 48,327
  • 33
  • 144
  • 170
  • By the way, if there's a syntax for my post id variables that would make this easier, that's totally cool too. – tybro0103 Oct 29 '10 at 20:56
  • If your string really has only one level of one kind of markup, then you could parse it awkwardly (by rescanning) using a regex. But in general, see: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – DigitalRoss Oct 29 '10 at 21:06

2 Answers2

7

The gsub method on String has a handy block variation that works well here:

>> s = "Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator."
=> "Lorem ipsum de color [post]57[/post] sit amet [post]103[/post] desectator."

>> posts = {"57" => "Angry Turtle", "103" => "Fuzzy Rabit"}
=> {"57"=>"Angry Turtle", "103"=>"Fuzzy Rabit"}

>> s.gsub(/\[post\](\d+)\[\/post\]/) {|m| posts[$1] }
=> "Lorem ipsum de color Angry Turtle sit amet Fuzzy Rabit desectator."

Your syntax couldn't be much less regex friendly though. Try not to use brackets and slashes.

jwarchol
  • 1,906
  • 15
  • 12
  • cool thanks... what kind of syntax would you recommend for such a thing? – tybro0103 Nov 01 '10 at 21:02
  • Anything that doesn't need to be escaped in the regexp and does't occur elsewhere in your normal text is a good bet. Some template languages use curly braces { } or double curly braces {{ }}. – jwarchol Nov 03 '10 at 03:51
2

(after reading your easier syntax comment) If you have a hash like

posts = {57 => "Angry Turtle", 103 => "Fuzzy Rabit"}

or an array like, ehm,

posts = []
posts[57] = "Angry Turtle"
posts[103] = "Fuzzy Rabbit"

then why not go for string interpolation?

"Lorem ipsum de color #{posts[57]} sit amet #{posts[103]} desectator."

And you're ready to go.

steenslag
  • 79,051
  • 16
  • 138
  • 171
  • Well my string is going to be input by a user. Plus my logic to get the post title won't be that direct. – tybro0103 Oct 30 '10 at 13:34