Ruby 字符串插入的问题

kai209209 · August 31, 2016 · Last by marksloan replied at September 10, 2016 · 2011 hits

今天在刷 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表示匹配到的第一个子集

You need to Sign in before reply, if you don't have an account, please Sign up first.