Ruby replace string with captured regex pattern

后端 未结 6 1999
庸人自扰
庸人自扰 2021-01-31 13:13

I am having trouble translating this into Ruby.

Here is a piece of JavaScript that does exactly what I want to do:

function get_code(str){
    return str         


        
6条回答
  •  囚心锁ツ
    2021-01-31 13:37

    Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

    "foo".gsub(/(o+)/, '\1\1\1')
    #=> "foooooo"
    

    But since you only seem to be interested in the capture group, note that you can index a string with a regex:

    "foo"[/oo/]
    #=> "oo"
    "Z_123: foobar"[/^Z_.*(?=:)/]
    #=> "Z_123"
    

提交回复
热议问题