字符串替换 Ruby 正则表达式
String Replacement Ruby regex
我需要用一个序列替换一串字符;我正在使用 gsub 方法
说,
name = "Tom"
这在文本中显示为 $(name)
我需要替换 $(name) with Tom
。
现在,它仅将 name
替换为 Tom
,而不是将 $(name)
替换为 Tom
。你能告诉我 gsub 会是什么样子吗?
str.gsub('$(name)', 'Tom')
或者,使用正则表达式
str.gsub(/$\(name\)/, 'Tom')
别忘了正确转义:
string = "My name is $(name)"
string.gsub(/$\(name\)/, "Tom")
# => My name is Tom
当然,您可以轻松地使其更通用:
substs = {
name: "Tom"
}
string.gsub(/$\((\w+)\)/) do |s|
substs[.to_sym]
end
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."
我需要用一个序列替换一串字符;我正在使用 gsub 方法
说,
name = "Tom"
这在文本中显示为 $(name)
我需要替换 $(name) with Tom
。
现在,它仅将 name
替换为 Tom
,而不是将 $(name)
替换为 Tom
。你能告诉我 gsub 会是什么样子吗?
str.gsub('$(name)', 'Tom')
或者,使用正则表达式
str.gsub(/$\(name\)/, 'Tom')
别忘了正确转义:
string = "My name is $(name)"
string.gsub(/$\(name\)/, "Tom")
# => My name is Tom
当然,您可以轻松地使其更通用:
substs = {
name: "Tom"
}
string.gsub(/$\((\w+)\)/) do |s|
substs[.to_sym]
end
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."