简体   繁体   English

使用gsub和块反转捕获组(Ruby)

[英]Reverse capture groups with gsub and a block (Ruby)

Is it possible to do something like this (without modifying this code): 是否可以做这样的事情(不修改此代码):

a = '1 and 2'
b = a.gsub(/(\d)/) do |match|
  # Print 2 and 1, reversing the captures matches
end

I know I can do a.gsub((\\d) and (\\d)) and then refer to the matched groups in the block as #$1 and #$2 but I was wondering if it's possible to capture both 1 and 2 in the block without doing this. 我知道我可以执行a.gsub((\\ d)和(\\ d)),然后将块中的匹配组称为#$ 1和#$ 2,但我想知道是否有可能同时捕获1和2中的1和2阻止不这样做。

更短的非gsub解决方案:

a.split(" ").reverse.join(' ')

It is impossible or difficult to do it exactly in that format, but here is something close: 完全以这种格式完成它是不可能或者很难的,但这里有一些接近:

"1 and 2".scan(/\d/).reverse.join(" and ")
# => "2 and 1"

如果您愿意,可以使用非gsub代码:

a.split(/[^\d]/).select{|s|!s.empty?}.reverse

I would do as below : 我会这样做:

a = '1 and 2'
a.split(" ").reverse.join(" ")
# => "2 and 1"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM