Ruby 区分大小写的替换
我有一个字符串,可能包含单词Ruby 区分大小写的替换,ruby,string,Ruby,String,我有一个字符串,可能包含单词“favorite”(美式英语)或大写的“favorite”。我想分别用英式拼写“favorite”或“favorite”替换它们,但不改变大写字母 我受够了 element.gsub!(/Favorite/i, 'Favourite') 它将始终大写第一个字母。我不想把它弄得太复杂,或者只是重复两个案例的替换。最好的解决方案是什么?您可以捕获第一个字母,然后使用\1反向引用将捕获的字母插入到后面: element.gsub!(/(f)avorite/i, '\1a
“favorite”
(美式英语)或大写的“favorite”
。我想分别用英式拼写“favorite”
或“favorite”
替换它们,但不改变大写字母
我受够了
element.gsub!(/Favorite/i, 'Favourite')
它将始终大写第一个字母。我不想把它弄得太复杂,或者只是重复两个案例的替换。最好的解决方案是什么?您可以捕获第一个字母,然后使用
\1
反向引用将捕获的字母插入到后面:
element.gsub!(/(f)avorite/i, '\1avourite')
^^^ ^^
看
(f)
捕获组与i
不区分大小写的修饰符将匹配f
或f
,替换模式中的\1
将粘贴回此字母
请注意,要替换整个单词,应使用:
此外,请注意替换字符串文字使用的单引号,如果使用双引号,则需要将反斜杠加倍
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
中的键(即使它包含键“honorable”
)。一个更完整的示例可能包括该单词作为键。gsub(/(f)avorite/i,“\1avorite”)
?谢谢,这很有效!如果这个词在美式拼写中是“美学”而在英语拼写中是“美学”呢?@sawa/\b(f)avorite\b/i
匹配aavorite
?@WiktorStribiżew你是对的。我不知怎么把你的()
错当成了()?
。
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."