开发者

how to change values between tags in a string

开发者 https://www.devze.com 2023-02-24 04:26 出处:网络
If I have the开发者_JAVA百科 following string: str=\"hello %%one_boy%%\'s something %%four_girl%%\'s something more\"

If I have the开发者_JAVA百科 following string:

str="hello %%one_boy%%'s something %%four_girl%%'s something more"

how would I edit it to get the following output from printing str:

"hello ONE_BOY's something FOUR_GIRL's something more"

I have been trying to use 'gsub' and 'upcase' methods but am struggling with the regex to get each word between my '%%' symbols.


ruby-1.9.2-p136 :066 > str.gsub(/%%([^%]+)%%/) {|m| $1.upcase}
 => "hello ONE_BOY's something FOUR_GIRL's something more" 

The [^%]+ says it will match 1 or more characters except %, and the $1is a global variable that stores the back reference to what was matched.


s.gsub(/%%([^%]+)%%/) { $1.upcase }


Here's a quick and dirty way:

"hello %%one_boy%%'s something %%four_girl%%'s something more".gsub(/(%%.*?%%)/) do |x|
    x[2 .. (x.length-3)].upcase
end

The x[2 .. (x.length-3)] bit slices out the middle of the match (i.e. strips off the leading and trailing two characters).


If you're able to choose the delimiters, you might be able to use String.interpolate from the Facets gem:

one_boy = "hello".upcase
str = "\#{one_boy}!!!"
String.interpolate{ str }    #=> "HELLO!!!"

But I'd first check that Facets doesn't cause any conflicts with Rails.


str.gsub(/%%([^%]+)%%/) { |match| $1.upcase }
0

精彩评论

暂无评论...
验证码 换一张
取 消