【发布时间】:2021-08-31 07:41:00
【问题描述】:
我有以下代码:
vars=["aaa","bbb","ccc"].join("|");
str="aaa has bbb has ccc"
# attempt ont
result = str.gsub(/+vars+/,"hello")
# attempt two
result = str.gsub("/"+vars+"/","hello")
puts result
如何将vars 的内容放入正则表达式中,以用hello 替换所有实例?
【问题讨论】:
-
你的意思是
result = str.gsub(Regexp.new(vars), "hello")? -
@WiktorStribiżew 是的,我刚刚意识到我做错了什么谢谢。
-
@WiktorStribiżew:更好,
Regexp.new(Regexp.union(["aaa","bbb","ccc"].map{|s| Regexp.escape(s)})) -
@SergioTulentsev 你能在答案中解释这个解决方案吗?
-
正则表达式文字也处理插值,因此更接近您的初始设计的解决方案是
/#{vars}/