Ignoring a character along with word boundary in regex

前端 未结 3 1308
甜味超标
甜味超标 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:38

    All that escaping in the Regexp.new is looking quite ugly. You could greatly simplify that by using a Regexp literal:

    word = 'below'
    text = "I said, 'look out below'"
    
    reg = /\b#{word}\b/i
    text.gsub!(reg, '\0')
    

    Also, you could use the modifier form of gsub! directly, unless that string is aliased in some other place in your code that you are not showing us. Lastly, if you use the single quoted string literal inside your gsub call, you don't need to escape the backslash.

提交回复
热议问题