区分大小写的替换

时间:2019-01-06 21:48:39

标签: ruby string

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

我坚持下去

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

始终将首字母大写。我不想使其变得过于复杂,或者只是重复两种情况的替换。最好的解决方案是什么?

2 个答案:

答案 0 :(得分:2)

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")。一个更完整的示例可能包含该单词作为关键字。

答案 1 :(得分:1)

您可以捕获第一个字母,然后使用\1后向引用将捕获的一个字母向后插入:

element.gsub!(/(f)avorite/i, '\1avourite')
               ^^^            ^^

请参见this Ruby demo

(f)捕获组与i不区分大小写的修饰符一起将匹配fF,并且替换模式中的\1将粘贴这封信回来了。

请注意,要替换整个单词,应使用word boundaries

element.gsub!(/\b(f)avorite\b/i, '\1avourite')
               ^^          ^^

此外,请注意用于替换字符串文字的单引号,如果使用双引号,则需要将反斜杠加倍。