我无法将其翻译成 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"
双引号中的 \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"
如果您需要使用正则表达式过滤某些结果,然后只使用捕获组,您可以执行以下操作:
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"
def get_code(str)
str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"
$
变量仅设置为匹配到块中:
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { "#{ $1.strip }" }
这也是在匹配上调用方法的唯一方法。这不会改变匹配,只有 strip
"\1" (保持不变):
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1".strip)
不定期副业成功案例分享
-e
的命令行上),更有可能看到 双引号:printf "Punkinhead the name" | ruby -ne 'puts gsub /.*(the name)/, "Jonathans \\1"'
,因为表达式提供给-e
通常用单引号括起来。"\\1"
而不是'\1'
。然后像"Z_123_2018".gsub(/\A(Z_\d+_)(\d{4})\z/, "\\1#{$2.to_i+1}") → "Z_123_2019"
这样的东西是可能的。