Ruby replace string with captured regex pattern

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

    \1 in double quotes needs to be escaped. So you want either

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

    or

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

    see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."

    That being said, if you just want the result of the match you can do:

    "Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)
    

    or

    "Z_sdsd: sdsd"[/^Z_.*(?=:)/]
    

    Note that the (?=:) is a non-capturing group so that the : doesn't show up in your match.

提交回复
热议问题