Ignoring a character along with word boundary in regex

前端 未结 3 1317
甜味超标
甜味超标 2020-12-20 00:51

I am using gsub in Ruby to make a word within text bold. I am using a word boundary so as to not make letters within other words bold, but am finding that this ignores word

3条回答
  •  借酒劲吻你
    2020-12-20 01:30

    The #{word} syntax doesn't work for regular expressions. Use Regexp.new instead:

    word = "below"
    text = "I said, 'look out below'"
    
    reg = Regexp.new("\\b#{word}\\b", true)
    text = text.gsub(reg, "\\0")
    

    Note that when using sting you need to escape \b to \\b, or it is interpreted as a backspace. If word may contain special regex characters, escape it using Regexp.escape.

    Also, by replacing the string to #{word} you may change casing of the string: "BeloW" will be replaced to "below". \0 corrects this by replacing with the found word. In addition, I added \\b at the beginning, you don't want to look for "day" and end up with "sunday".

提交回复
热议问题