我正在寻找一种方法来搜索字符串中所有出现的模式,对返回的字符串执行一些重要的操作,然后替换它。
鲁比的 String#gsub!方法不太合适,因为我需要获取返回的事件,然后对其进行操作以得出将用于替换它的值。
鲁比的 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
与 block 一起使用,所以
string.gsub(/\s[aeiou]\w{1,}/i) do |word|
word.upcase
end
关于Ruby:查找字符串中所有出现的模式,操作,然后替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107691/