使用regexp更改javascript函数到ruby函数

时间:2014-06-01 09:24:42

标签: javascript ruby-on-rails ruby regex

这是javascript函数。

var e2k = (function() {
    var en_h = "rRseEfaqQtTdwWczxvg";
    var reg_h = "[" + en_h + "]";

    var en_b = {k:0,o:1,i:2,O:3,j:4,p:5,u:6,P:7,h:8,hk:9,ho:10,hl:11,y:12,n:13,nj:14,np:15,nl:16,b:17,m:18,ml:19,l:20};
    var reg_b = "hk|ho|hl|nj|np|nl|ml|k|o|i|O|j|p|u|P|h|y|n|b|m|l";

    var en_f = {"":0,r:1,R:2,rt:3,s:4,sw:5,sg:6,e:7,f:8,fr:9,fa:10,fq:11,ft:12,fx:13,fv:14,fg:15,a:16,q:17,qt:18,t:19,T:20,d:21,w:22,c:23,z:24,x:25,v:26,g:27};
    var reg_f = "rt|sw|sg|fr|fa|fq|ft|fx|fv|fg|qt|r|R|s|e|f|a|q|t|T|d|w|c|z|x|v|g|";

    var reg_exp = new RegExp("("+reg_h+")("+reg_b+")(("+reg_f+")(?=("+reg_h+")("+reg_b+"))|("+reg_f+"))","g");

    var replace = function(str,h,b,f) {
            return String.fromCharCode(en_h.indexOf(h) * 588 + en_b[b] * 28 + en_f[f] + 44032);
    };  

    return (function(str) {
            return str.replace(reg_exp,replace);
    }); 
})();

此功能从英语拼写翻译为韩语。

例如,' gksrnr' => "한국"

我应该将此功能更改为ruby功能。

所以,我改变了

var reg_exp = new RegExp("("+reg_h+")("+reg_b+")(("+reg_f+")(?=("+reg_h+")("+reg_b+"))|("+reg_f+"))","g");

reg_exp = /#{reg_h} && #{reg_b} && (#{reg_f} && (?=#{reg_h} && #{reg_b}) | #{reg_f})/

在" spdlqj"("네이버")的情况下,它运作良好......

但是在" gksrnr"("한국"),它不能很好地运作..

它无法捕捉最终的辅音。

那么有人可以建议正则表达式吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

这有效:

def e2k(string)

  en_h = "rRseEfaqQtTdwWczxvg"
  reg_h = "[" + en_h + "]"

  en_b = {'k' =>0, 'o' =>1, 'i' =>2, 'O' =>3, 'j' =>4, 'p' =>5, 'u' =>6, 'P' =>7, 'h' =>8, 'hk' =>9, 'ho' =>10, 'hl' =>11, 'y' =>12, 'n' =>13, 'nj' =>14, 'np' =>15, 'nl' =>16, 'b' =>17, 'm' =>18, 'ml' =>19, 'l' =>20}
  reg_b = "hk|ho|hl|nj|np|nl|ml|k|o|i|O|j|p|u|P|h|y|n|b|m|l";

  en_f = {"" => 0, 'r' =>1, 'R' =>2, 'rt' =>3, 's' =>4, 'sw' =>5, 'sg' =>6, 'e' =>7, 'f' =>8, 'fr' =>9, 'fa' =>10, 'fq' =>11, 'ft' =>12, 'fx' =>13, 'fv' =>14, 'fg' =>15, 'a' =>16, 'q' =>17, 'qt' =>18, 't' =>19, 'T' =>20, 'd' =>21, 'w' =>22, 'c' =>23, 'z' =>24, 'x' =>25, 'v' =>26, 'g' =>27}
  reg_f = "rt|sw|sg|fr|fa|fq|ft|fx|fv|fg|qt|r|R|s|e|f|a|q|t|T|d|w|c|z|x|v|g|"

  reg_exp = Regexp.new("("+reg_h+")("+reg_b+")(("+reg_f+")(?=("+reg_h+")("+reg_b+"))|("+reg_f+"))","g")

  replace = ->(str) {
    h,b,f = Regexp.last_match[1..3]
    (en_h.index(h) * 588 + en_b[b] * 28 + en_f[f] + 44032).chr(Encoding::UTF_8)
  }
  string.gsub(reg_exp, &replace)
end

e2k("spdlqj")  #=> "네이버"
e2k("gksrnr")  #=> "한국"

但请注意,它非常不像红宝石。请将其发布到codereview.stackexchange.com,以便我们清理它。