简体   繁体   English

用gsub替换带有重音符号的正则表达式

[英]Replace with gsub a regexp with accents

I try to get a function for setting < b > around catched strings (case insensitive), like this : 我尝试获得一个在捕获的字符串周围设置<b>的函数(不区分大小写),如下所示:

bold_string("Hello everyone","o")
> "Hell<b>o</b> every<b>o</b>ne"

bold_string("HEllo evEryonE", "e")
> "H<b>E</b>llo <b>e</b>v<b>E</b>ryon<b>E<b/>"

Now, my function looks like that : 现在,我的函数如下所示:

def bold_string(str, search)
  str.gsub(/(#{search})/i, '<b>\1</b>')
end

It works perfectly with the previous examples, but not with the words having some accents. 它与前面的示例完美地结合在一起,但不适用于带有重音符号的单词。 There are the results I expect : 有我期望的结果:

bold_string("Petite bête", "e")
> "P<b>e</b>tit<b>e</b> b<b>ê</b>t<b>e</b>"

bold_string("Petite bête", "ê")
> "P<b>e</b>tit<b>e</b> b<b>ê</b>t<b>e</b>"

In other words, I have to find a regex like /search/i, it says "you have to find the word 'search' or the word 'search' with some accents". 换句话说,我必须找到一个像/ search / i这样的正则表达式,它表示“您必须找到带有某些重音的单词'search'或'search'”。

edit : 编辑:

I see I was too simplist with my example... It should works with string and not simply chars : 我看到我的例子太简单了……它应该适用于string而不是chars:

bold_string("Petite bête", "êt")
> "P<b>et</b>ite</b> b<b>êt</b>e"

Regards 问候

Pierre 皮埃尔

edit2 : I used the solution of FJ with this new function edit2:我将此新功能用于FJ解决方案

def regex_from_string_including_accents(str)
  accents = ['aàâ', 'eéèêë', 'oöô' 'iî']
  return str.gsub(/./) do |letter|
    accent_group = accents.detect{|group| group.include?(letter)}
    accent_group ? "[#{accent_group}]" : letter
  end
end

You could do something like the following: 您可以执行以下操作:

def bold_string(str, search)
  h = { "e" => "[eéê]", "a" => "[aáâ]" }
  regex = search.gsub(/./) {|s| h.fetch(s, s)}
  str.gsub(/(#{regex})/i, '<b>\1</b>')
end

Obviously this just shows you how to get started, you will need to fill h with additional accented versions of characters. 显然,这只是向您显示了入门方法,您需要用其他带有重音符号的字符填充h

Example: http://ideone.com/KukiKc 例如: http//ideone.com/KukiKc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM