忽略正则表达式中的字符和单词边界 [英] Ignoring a character along with word boundary in regex

查看:173
本文介绍了忽略正则表达式中的字符和单词边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Ruby中使用gsub来使文本内的单词加粗.我正在使用单词边界,以便不要使其他单词内的字母变成粗体,但是发现这会忽略后面带有引号的单词.例如:

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}\b/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?

推荐答案

Regexp.new中转义的所有内容看起来都很丑陋.您可以使用Regexp文字来简化此操作:

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, '<b>\0</b>')

此外,您可以直接使用gsub!的修饰符形式,除非该字符串在您未向我们显示的代码中的其他位置带有别名.最后,如果在gsub调用中使用单引号引起来的字符串文字,则无需转义反斜杠.

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.

这篇关于忽略正则表达式中的字符和单词边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆