用捕获的正则表达式模式替换字符串
我无法将此翻译成Ruby。用捕获的正则表达式模式替换字符串
下面是一段JavaScript这不正是我想做的事:
function get_code(str){
return str.replace(/^(Z_.*): .*/,"$1");
}
我已经试过gsub,sub,并且replace但没有似乎做什么,我期待的。
这里是我试过的东西例子:
"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'
用于替换(单引号是很重要的,否则你需要躲避\
):
"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"
但因为您似乎只对捕获组感兴趣,请注意,您可以使用正则表达式为字符串编制索引:
"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"
请注意,这只适用于替换字符串在**单引号**内。我花了5分钟弄清楚了这一点。 – 2013-02-09 00:30:54
@MarkThomas - 通常我们会在没有阅读全部答案的情况下先尝试顶部/接受的答案。这似乎通常是解决问题的最有效手段。给Vicky休息一下! :) – 2014-01-31 03:43:26
@VickyChijwani好评,但也要注意,当使用Ruby inline(在命令行中用'-e')时,更可能看到**双引号**:'printf“Punkinhead名字为”| ruby -ne'将gsub /。*(名称)/,“Jonathans \\ 1”''提供给'-e'的表达式通常用单引号括起来。 – 2017-07-24 12:52:19
def get_code(str)
str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"
\1
用双引号需要转义。所以,你想要么
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")
或
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')
看到the docs on gsub它说:“如果这是一个双引号字符串,这两个反向引用必须通过额外的反斜杠。”
话虽这么说,如果你只是想本场比赛的结果,你可以这样做:
"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)
或
"Z_sdsd: sdsd"[/^Z_.*(?=:)/]
注意,(?=:)
是一个非捕获组,以便:
没有出现在你的比赛中。
"foobar".gsub(/(o+)/){|s|s+'ball'}
#=> "fooballbar"
不知道我能做到这一点。太好了! – vreen 2016-06-07 21:42:42
如果你需要使用正则表达式过滤掉一些结果,然后只使用捕获组,你可以做到以下几点:
str = "Leesburg, Virginia 20176"
state_regex = Regexp.new(/,\s*([A-Za-z]{2,})\s*\d{5,}/)
# looks for the comma, possible whitespace, captures alpha,
# looks for possible whitespace, looks for zip
> str[state_regex]
=> ", Virginia 20176"
> str[state_regex, 1] # use the capture group
=> "Virginia"
你应该表现出实际的代码你已经什么试过。 – Amber 2012-03-27 22:12:47
@Amber我把我试过的样品。 – 2012-03-27 22:17:29