我正在寻找一种方法来搜索字符串中所有出现的模式,对返回的字符串执行一些重要的操作,然后替换它。
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
答案 0 :(得分:9)
您可以将gsub
与块一起使用,所以
string.gsub(/\s[aeiou]\w{1,}/i) do |word|
word.upcase
end
答案 1 :(得分:3)
String#gsub!
可以与块一起使用,该块传递匹配的字符串。然后使用块的结果替换匹配:
# 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."
string.gsub!(/\s[aeiou]\w{1,}/i) { |m| m.upcase }
答案 2 :(得分:2)
你的意思是这样的:
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."
copy = string
# 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
copy.gsub! word, word.upcase
end
# Print the modified string
puts copy
答案 3 :(得分:0)
您不必使用gsub
:
string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit."
string.split.map {|word| "aeiou".include?(word[0]) ? word.capitalize : word}.join(' ')
# => "Lorem Ipsum dolor sit Amet, consectetur Adipisicing Elit."