正则表达式(Javascript) – 取一个扰乱的单词并找到一个解密的匹
我列出了一个名为theList的变量中存储的英语词典中的所有单词(270,000个单词).
我有一个混乱的单词,我想通过匹配单词列表来解读. 最初,我认为以下代码可以解决问题,但它不能很好地工作. var theList; // Contains all the words in the English dictionary. var word = "iexospensr"; // The word I want to unscramble. var matches = word.match(new RegExp("^["+word+"]{"+word.length+"}$","gim")); 我已经预期“EXPRESSION”作为解读结果,但我得到了更多的结果(如下所列). EERINESSES,表达者,表达,IRONNESSES,ISOSPORIES,NONPERSONS,NONPROSSES,NOSINESSES,OPENNESSES,压迫,ORNERINESS,PENSIEROSO,PENSIONEER,退休人员,意大利香肠,PERSIENNES,PERSONISES,PIPINESSES,PIXINESSES,POORNESSES,PORINESSES,占有,占有者,PREEXPOSES,PREPOSSESS,PREPPINESS,PRESENSION,PRIORESSES,PRISSINESS,PROPENSION,适当性,REINSPIRES,REPRESSERS,镇压,抑制子,RESERPINES,RESPONSERS,RESPONSORS,RIPENESSES,ROPINESSES,ROSINESSES,SERENENESS,SEXINESSES,SIXPENNIES,SNIPPINESS,SORENESSES,SPINNERIES 也许,如果我能找到一种方法来告诉正则表达式只考虑字符串单词中的每个字母,而不管字母的顺序如何.所以最终结果将是这些字母组合的数组,而不是排列(我现在拥有的). 任何帮助,将不胜感激. 编辑: 如果你有一个更好的解决方案(性能方面),它会有所帮助. 这个问题的最佳解决方案似乎是按字母顺序重新排序字谜,以及整个单词列表并将单词与列表中的每个项目进行匹配. 这是代码: var textList; // the entire dictionary var list = textList.match(/^.*$/gim); var sortedList = []; list.forEach(function(element,index,array) { sortedList[index] = element.split("").sort().join(""); }); function unscramble(word) { word = word.toUpperCase().split("").sort().join(""); var matches = []; for (var i = 0; i < list.length; i++) { if (word.indexOf(sortedList[i]) >= 0) { if (!matches[list[i].length]) matches[list[i].length] = []; matches[list[i].length].push(list[i]); } } return matches; } 解决方法
不要使用正则表达式,有更简单的方法,如果你将字典拆分成单词而不是做一个巨大的字符串:
>一个扰乱的单词由字母出现的频率定义: //WARNING,untested code alphabet = 'qwertyuiopasdfghjklzxcvbnm'; function empty_frequences(){ var freqs = {}; var i=; for(i=0; i<alphabet.length; i++){ freqs[alphabet[i]] = 0; } return freqs; } function frequences(str){ var freqs = empty_frequences(); var i; for(i=0; i<str.length; i++){ freqs[str[i]] += 1; } } >使用此事实查找字典中的所有匹配项 function matcher(word){ //returns a function that matchs against this word var word_freqs = frequences(word); function do_the_match(word2){ var freqs2 = frequences(word2); var i,c; for(i=0; i<alphabet.length; i++){ c = alphabet[i] if(freqs[c] > freqs2[c]){return false;} //change > to != to allow only strict anagrams } return true; } return do_the_match; } function main(word,dict){ var mf = matcher(word); var i,matcheds = []; for(i=0; i<dict.length; i++){ if(mf(dict[i])){ matcheds.push(dict[i]); } } return matcheds; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |