Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby - Ignoring a character along with word boundary in regex

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 words that have a quote after them. For example:

text.gsub(/#{word}/i, "<b>#{word}</b>")

text = "I said, 'look out below'"
word = below

In this case the word below is not made bold. Is there any way to ignore certain characters along with a word boundary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 = /#{word}/i
text.gsub!(reg, '<b></b>')

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...