Ruby 字符串插入的问题

kai209209 · 2016年08月31日 · 最后由 marksloan 回复于 2016年09月10日 · 2012 次阅读

今天在刷 codewars 的题目的时候遇到了一题,要把一串数字中奇数之间插入破折号

比如输入数字 454793,返回的是 '4547-9-3'

然后看别人的解决方案

def insert_dash(num)
  num.to_s.gsub(/(?<=[13579])([13579])/, '-\1')
end

我想知道这个 gsub 第二个参数里的 \1 是什么意思啊?为什么加了这个就能正确插入而不是把数字给替换?

整几个例子验证一下就知道什么意思了,真心不难。😅

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form \\d, where d is a group number, or \\k<n>, where n is a group name.

"hello".gsub(/([aeiou])/, '<\1>')             #=> "h<e>ll<o>"
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}')  #=> "h{e}ll{o}"

\0是匹配到的全部结果 \1表示匹配到的第一个子集

需要 登录 后方可回复, 如果你还没有账号请 注册新账号