此字符串替换有效:
"reverse, each word".gsub(/(\w+)/, "\\1a")
=> "reversea, eacha worda"
和这样,单引号基本相同:
"reverse, each word".gsub(/(\w+)/, '\1a')
=> "reversea, eacha worda"
但如果我尝试反转字符串,则会失败:
"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)
=> "a1\\, a1\\ a1\\"
我玩过它,但似乎无法让相反的操作起作用。
答案 0 :(得分:9)
我一直碰到这个。块捕获组在块范围内可用,因此重写如下:
"reverse, each word".gsub(/(\w+)/) { |match| $1.reverse + "a" }
或者由于您的匹配是群组,因此您可以完全省略该群组
"reverse, each word".gsub(/\w+/) { |match| match.reverse + "a" }
答案 1 :(得分:0)
您确实命令ruby将所有出现的/(\ w +)/替换为“\ 1a”.reverse
"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)
你可能想要反转结果而不是替换字符串:
"reverse, each word".gsub(/(\w+)/, "\\1a").reverse