简体   繁体   中英

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.

更短的非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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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