Ruby replace string with captured regex pattern

后端 未结 6 1963
庸人自扰
庸人自扰 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:49

    $ variables are only set to matches into the block:

    "Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { "#{ $1.strip }" }
    

    This is also the only way to call a method on the match. This will not change the match, only strip "\1" (leaving it unchanged):

    "Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1".strip)
    

提交回复
热议问题