Replace text inside curly brackets (including the brackets themselves) in a string using Ruby and gsub
I have a string "This is my {foo} string".
开发者_StackOverflow中文版I want to replace the contents of the curly brackets with some manipulated value e.g.:
"This is my FOO string"
I have got this far:
result = mystring.gsub(/\{(.*?)\}/){|m| m.upcase}
But this returns "This is my {FOO} string" - i.e. the curly brackets are still there.
How do I phrase my regular expression so that the curly brackets are also replaced?
The string that is yielded is the whole match, so it includes the braces. Since you only want to work with the part in the first capturing group, you can use $1
instead of m
in the block.
精彩评论