regexrubystring

Case-sensitive replacement


I have a string that may include the word "favorite" (in American English) or the capitalised "Favorite". I want to substitute them with the British spelling "favourite" or "Favourite" respectively without changing the capitalisation.

I'm stuck with

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

which will always capitalise the first letter. I don't want to make it too complicated or just repeat the substitution for the two cases. What is the best solution?


Solution

  • You may capture the first letter and then use a \1 backreference to insert the captured one back:

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

    See this Ruby demo.

    The (f) capturing group, together with the i case insensitive modifier, will match f or F, and \1 in the replacement pattern will paste this letter back.

    Note that to replace whole words, you should use word boundaries:

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

    Also, mind the single quotes used for the replacement string literal, if you use double quotation marks, you will need to double the backslash.