You may use
text.downcase.gsub(/(?<!\w)#{Regexp.escape(lookup_term)}(?!\w)/, replace_with_term)
If you do not really want to get the string turned into lowercase, but just want case insensitive matching, use the /i
modifier and remove .downcase
:
text.gsub(/(?<!\w)#{Regexp.escape(lookup_term)}(?!\w)/i, replace_with_term)
See the Ruby demo online.
The resulting regex will look like /(?<!\w)check\ \+(?!\w)/
, see Rubular demo.
Note that \b
meaning is context-dependent, and matches an empty space (a location)
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
The (?<!\w)check\ \+(?!\w)
pattern contains unambiguous word boundaries, they always match the same way:
(?<!\w)
- a left-hand word boundary, requires a start of string position or any non-word character immediately to the left of the current location
check\ \+
- check
, space and +
(?!\w)
- a right-hand word boundary, requires an end of string position or any non-word character immediately to the right of the current location.