Ruby 用捕获的正则表达式模式替换字符串 [英] Ruby replace string with captured regex pattern

查看:41
本文介绍了Ruby 用捕获的正则表达式模式替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将其翻译成 Ruby.

I am having trouble translating this into Ruby.

这是一段 JavaScript,它完全符合我的要求:

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

function get_code(str){
    return str.replace(/^(Z_.*): .*/,"$1")​​​​​​​​​​​​​​​​​​​​​​​​​​​;
}

我尝试过 gsubsubreplace 但似乎没有人做我期望的.

I have tried gsub, sub, and replace but none seem to do what I am expecting.

以下是我尝试过的示例:

Here are examples of things I have tried:

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { |capture| capture }
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "$1")
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "#{$1}")
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\1")
"Z_sdsd: sdsd".gsub(/(.).*/) { |capture| capture }

推荐答案

尝试用'\1'进行替换(单引号很重要,否则需要转义\):

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"

这篇关于Ruby 用捕获的正则表达式模式替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆