Ruby on Rails Sunday, September 30, 2012

Quoting S Ahmed <sahmed1020@gmail.com>:
> I am trying this:
>
> I want to replace all the text in between java comments:
>
> /* start */
> replace this text here
> /* end */
>
>
> I'm trying:
>
> text.gsub(//* start */(.*)/* end *//im, replace_with)
>
> But i'm getting errors relating to expecting keyword_end.
>
> How should I be escaping /* and */ ?

Yes,
text.gsub(/\/\* start \*\/(.*)\/\* end \*\//im, replace_with)

Slightly simpler
text.gsub(%r{/\* start \*/(.*)/\* end \*/}im, replace_with)

>
> Also, does string interpolation work in gsub regex? Say I had variables
> like:
>
> start_tag = "/* start */"
> end_tag = "/* end */"
>
> I want to do:
>
> text.gsub("#{start_tag}(.*)#{end_tag}", replace_with)
>

gsub takes regex, not strings

text.gsub(/#{start_tag}(.*)#{end_tag}/, replace_with)

Special characters do need to be escaped in start_tag and end_tag, but in this
case only the asterisks, not the slashes.

HTH,
Jeffrey

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment