gpt4 book ai didi

ruby - 区分大小写的替换

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:56 25 4
gpt4 key购买 nike

我有一个字符串,可能包含单词 "favorite"(美式英语)或大写的 "Favorite"。我想分别用英式拼写 "favourite""Favourite" 替换它们,而不改变大小写。

我坚持

element.gsub!(/Favorite/i, 'Favourite')

始终将第一个字母大写。我不想让它变得太复杂,或者只是重复这两种情况的替代。什么是最佳解决方案?

最佳答案

subs = {
'center' =>'centre', 'defense' =>'defense',
'behavour' =>'behaviour', 'apologize' =>'apologise',
'maneuver' =>'manoeuvre', 'pediatric' =>'paediatric',
'traveled' =>'travelled', 'honor' =>'honour',
'favorite' =>'favourite', 'esthetics' =>'aesthetics'
}

str = "My Favorite uncle, Max, an honorable gent, is \
often the Center of attention at parties, mainly \
because he has a great sense for Esthetics. \
I apologize for my clumsy maneuver.".squeeze(' ')

str.gsub(/\b\p{Alpha}+\b/) do |word|
key = word.downcase
if subs.key?(key)
new_word = subs[key]
new_word.capitalize! if word.match?(/\A\p{Upper}/)
word = new_word
end
word
end
#=> "My Favourite uncle, Max, an honorable gent, is \
# often the Centre of attention at parties, mainly \
# because he has a great sense for Aesthetics. \
# I apologise for my clumsy manoeuvre."

"honorable" 未被修改,因为它不是散列 subs 中的键(即使它包含键 "honor" ).更完整的示例可能包括该词作为键。

关于ruby - 区分大小写的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54066259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com