我正在尋找一種方法來搜索字符串中所有出現的模式,對返回的字符串執行一些非平凡的操作,然後代替它。Ruby:查找所有出現的字符串中的模式,操作並替換
Ruby的String#gsub!方法不太合適,因爲我需要接收返回的出現,然後操作它以提供將用於替換它的值。
Ruby的String#scan方法當然可以用來查找所有出現的模式,但是我不知道如何在我對它們進行必要的更改後替換返回的出現。
下面的代碼示例並不是我實際上正在處理的內容,它演示了我試圖完成的事情。
# String
string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
# Look for all words that start with a vowel
string.scan(/\s[aeiou]\w{1,}/i).each do |word|
# Manipulate the words that match the pattern
word.upcase
# Replace the word in the string with the manipulated value
# Need some help here
end
# Print the modified string
puts string
或'gsub(/ \ s [aeiou] \ w {1,}/i,&:upcase)'如果'upcase'是真正被使用的。 –