字符串替换Ruby正则表达式

时间:2015-07-07 18:58:40

标签: ruby regex string gsub

我需要用序列替换一串字符;我正在使用gsub方法

说,

name = "Tom"

这会在$(name)文本中显示,我需要替换$(name) with Tom

现在,它只用name替换Tom而用$(name)替换Tom。你能告诉我gsub会是怎样的吗?

3 个答案:

答案 0 :(得分:3)

不要忘记妥善解决问题:

string = "My name is $(name)"

string.gsub(/\$\(name\)/, "Tom")
# => My name is Tom

当然,您可以轻松地使其更通用:

substs = {
  name: "Tom"
}

string.gsub(/\$\((\w+)\)/) do |s|
  substs[$1.to_sym]
end

答案 1 :(得分:2)

str.gsub('$(name)', 'Tom')

或者,使用正则表达式

str.gsub(/\$\(name\)/, 'Tom')

答案 2 :(得分:2)

str = "and this appears in a text as $(name) i need to replace $(name) with Tom."
str.tr!("$()","%{}") # use ruby's sprintf syntax %{name}
some_name = "Tom"

p str % {name: some_name}
# => "and this appears in a text as Tom i need to replace Tom with Tom."