Everything in this code works properly, except the contents of the $1 variable aren’t being properly displayed. According to my tests, all the matching is being done properly, I am just having trouble figuring out how to actually output the contents of $1.
codeTags = {
/\[b\](.+?)\[\/b\]/m => "<strong>#{$1}</strong>",
/\[i\](.+?)\[\/i\]/m => "<em>#{$1}</em>"
}
regexp = Regexp.new(/(#{Regexp.union(codeTags.keys)})/)
message = (message).gsub(/#{regexp}/) do |match|
codeTags[codeTags.keys.select {|k| match =~ Regexp.new(k)}[0]]
end
return message.html_safe
Thank you!
As soon as you do this:
The
#{$1}bits in the values are interpolated using whatever happens to be in$1at the time. The values will most likely be"<strong></strong>"and"<em></em>"and those aren’t very useful.And
regexpis already a regular expression object sogsub(/#{regexp}/)should be justgsub(regexp). Similar things apply to the keys ofcodeTags, they’re already regular expression objects so you don’t need toRegexp.new(k).I’d change the whole structure, you’re overcomplicating things. Just something simple like this would be fine for only two replacements:
If you try to do it all at once you’ll have problems with nesting in something like this:
You’d end up having to use a recursive
gsuband possibly some lambdas if you wanted to properly handle things like that with a single expression.There are better things to spend your time on than trying to be clever on something like this.
Response to comments: If you have more bb-tags and some smilies to worry about and several messages per page then you should HTMLify each message when you create it. You could store only the HTML version or both HTML and BB-Code versions if you want the BB-Code stuff around for some reason. This way you’d only pay for the HTMLification once per message and producing your big lists would be nearly free.