[英]Reverse capture groups with gsub and a block (Ruby)
是否可以做這樣的事情(不修改此代碼):
a = '1 and 2'
b = a.gsub(/(\d)/) do |match|
# Print 2 and 1, reversing the captures matches
end
我知道我可以執行a.gsub((\\ d)和(\\ d)),然后將塊中的匹配組稱為#$ 1和#$ 2,但我想知道是否有可能同時捕獲1和2中的1和2阻止不這樣做。
更短的非gsub解決方案:
a.split(" ").reverse.join(' ')
完全以這種格式完成它是不可能或者很難的,但這里有一些接近:
"1 and 2".scan(/\d/).reverse.join(" and ")
# => "2 and 1"
如果您願意,可以使用非gsub
代碼:
a.split(/[^\d]/).select{|s|!s.empty?}.reverse
我會這樣做:
a = '1 and 2'
a.split(" ").reverse.join(" ")
# => "2 and 1"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.