简体   繁体   English

不可能用gsub替换字符

[英]impossible to replace the character with gsub

we import a file and in the file there for special crater at first I try encoding methods and decoding ruby and nothing happens, so I used gsub. 我们导入一个文件,然后在文件中放入特殊的坑,我首先尝试编码方法并解码红宝石,但没有任何反应,因此我使用了gsub。 work it moist as the character group Ì© and ̤ For the rest no problem replaces me. 像字符组̩̤一样潮湿,其余的都没问题代替我。

here method replace 这里方法替换

def replace_chars(name)

  chars = {
          "Ž"   => 'é',
          "Â"    => "ç",
          "‘"  => "ë",
          "â„¢"  => "ô",
          "̤" => "ç",
          "Ì©" => "é",
          "•"  => "ï"
        }

  puts "before #{name}"
  chars.each do |key,value|
    name.gsub!(key,value)
  end
  puts "after #{name}"
end

if I but my method 如果我但是我的方法

replace_chars('̤liver Žponime')

here puts the output of the method, the first he has not succeeded in changing the word but in the second he has made the change. 在这里放置方法的输出,第一个他没有成功更改单词,但是第二个他做了更改。

output : after ÃŒç¤liver éponime 输出: after ÃŒç¤liver éponime

I do not understand why he does not want to take my character ̤ and Ì© . 我不明白为什么他不希望把我的性格̤̩

Here is another solution that will avoid the need to iterate all the characters and will replace matches. 这是另一种解决方案,它将避免重复所有字符并替换匹配项。 @Prashant4020 is correct that you will need to order the keys in descending length or at least sort them by length before performing this operation as  right now will match and substitute prior to ̤ . @ Prashant4020是正确的,在执行此操作之前,您将需要按降序对密钥进行排序或至少按长度对它们进行排序,因为Â现在将匹配并替换̤

def replace_chars(name
  chars = {
    "̤" => "ç",
    "Ì©" => "é",
    "•"  => "ï",
    "â„¢"  => "ô",
    "Ž"   => 'é',
    "‘"  => "ë",
    "Â"    => "ç"
 }
  #name.gsub!(/#{chars.keys.join('|')}/,chars)
  #as suggested by @steenslag Regexp::union is definitely less of a hack
  name.gsub!(Regexp.union(chars.keys),chars) 
  #translates to name.gsub!(/̤|Ì©"|•|â„¢|Ž|‘|Â/,{"̤" => "ç","Ì©"=>"é","•"=>"ï","â„¢"=>"ô","Ž"=>'é',"‘"=>"ë","Â"=>"ç"})
end

This creates a regex that will match the keys from the chars hash and then use the values to substitute the keys. 这将创建一个正则表达式,它将与chars哈希中的键匹配,然后使用值替换键。 This way gsub! 这样gsub! will not be called for keys that do not exist in the name at all. name中根本不存在的键将不会被调用。

Replace your code with this: 用以下代码替换代码:

def replace_chars(name)
  chars = {
      "̤" => "ç",
      "Ì©" => "é",
      "•"  => "ï",
      "â„¢"  => "ô",
      "Ž"   => 'é',
      "‘"  => "ë",
      "Â"    => "ç"          
    }
  puts "before #{name}"
  chars.each do |key,value|
    name.gsub!(key,value)
  end
  puts "after #{name}"
end

replace_chars('̤liver Žponime')
before ̤liver Žponime
after çliver éponime

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

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