查找和替换为字典,仅使用键一次 [英] Find and replace by a dictionary, using keys only once
本文介绍了查找和替换为字典,仅使用键一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是的后续操作在字典中.
我的问题是...
-
第一个是:我相信这会匹配不完整的单词.就像我的词典中的short一样,它很快就会与单词匹配.我将如何停止呢?
The first is: I believe this matches words that are not whole. Like if short is in my dictionary it matches the word shortly. How would I stop this?
第二个不是很重要,但会很好的是:我将如何制作它,使其每个内容仅匹配一次?如此短就不会在同一内容区域内被定义两次.
And the second not so important but would be nice is: How would I make it so it only matches once per content? So short doesn't get defined twice within the same content area.
谢谢!
推荐答案
我已经实现了以下附加要求:
I have implemented the following additional requirements:
- 寻找
short
时不匹配shortly
(因为shortly
是另一个词) - 仅在字典中使用键一次.
输入示例:键=foo
,替换=bar
,内容=foo foo
.
输出:bar foo
(仅替换第一个foo
).
- Do not match
shortly
when looking forshort
(becauseshortly
is a different word) - Use keys in the dictionary only once.
Example input: key=foo
, replacement=bar
, content=foo foo
.
Output:bar foo
(only the firstfoo
is replaced).
演示: http://jsfiddle.net/bhGE3/3/
Demo: http://jsfiddle.net/bhGE3/3/
用法:
- 定义一个
dictionary
.每个密钥只能使用一次. - 定义
content
.将基于该字符串创建一个新字符串. - (可选),定义一个
replacehandler
函数.每次比赛都调用此函数.返回值将用于替换匹配的短语.
默认值replacehandler
将返回字典的匹配短语.该函数应带有两个参数:key
和dictionary
. - 致电
replaceOnceUsingDictionary(dictionary, content, replacehandler)
- 处理输出,例如向用户显示
content
.
- Define a
dictionary
. Each key will be used only once. - Define
content
. A new string will be created, based on this string. - Optionally, define a
replacehandler
function. This function is called at each match. The return value will be used to replace the matched phrase.
The defaultreplacehandler
will return the dictionary's matching phrase. The function should take two arguments:key
anddictionary
. - Call
replaceOnceUsingDictionary(dictionary, content, replacehandler)
- Process the output, eg. show
content
to the user.
代码:
var dictionary = {
"history": "war . ",
"no": "in a",
"nothing": "",
"oops": "",
"time": "while",
"there": "We",
"upon": "in",
"was": "get involved"
};
var content = "Once upon a time... There was no history. Nothing. Oops";
content = replaceOnceUsingDictionary(dictionary, content, function(key, dictionary){
return '_' + dictionary[key] + '_';
});
alert(content);
// End of implementation
/*
* @name replaceOnceUsingDictionary
* @author Rob W http://stackoverflow.com/users/938089/rob-w
* @description Replaces phrases in a string, based on keys in a given dictionary.
* Each key is used only once, and the replacements are case-insensitive
* @param Object dictionary {key: phrase, ...}
* @param String content
* @param Function replacehandler
* @returns Modified string
*/
function replaceOnceUsingDictionary(dictionary, content, replacehandler) {
if (typeof replacehandler != "function") {
// Default replacehandler function.
replacehandler = function(key, dictionary){
return dictionary[key];
}
}
var patterns = [], // \b is used to mark boundaries "foo" doesn't match food
patternHash = {},
oldkey, key, index = 0,
output = [];
for (key in dictionary) {
// Case-insensitivity:
key = (oldkey = key).toLowerCase();
dictionary[key] = dictionary[oldkey];
// Sanitize the key, and push it in the list
patterns.push('\\b(?:' + key.replace(/([[^$.|?*+(){}])/g, '\\$1') + ')\\b');
// Add entry to hash variable, for an optimized backtracking at the next loop
patternHash[key] = index++;
}
var pattern = new RegExp(patterns.join('|'), 'gi'),
lastIndex = 0;
// We should actually test using !== null, but for foolproofness,
// we also reject empty strings
while (key = pattern.exec(content)) {
// Case-insensitivity
key = key[0].toLowerCase();
// Add to output buffer
output.push(content.substring(lastIndex, pattern.lastIndex - key.length));
// The next line is the actual replacement method
output.push(replacehandler(key, dictionary));
// Update lastIndex variable
lastIndex = pattern.lastIndex;
// Don't match again by removing the matched word, create new pattern
patterns[patternHash[key]] = '^';
pattern = new RegExp(patterns.join('|'), 'gi');
// IMPORTANT: Update lastIndex property. Otherwise, enjoy an infinite loop
pattern.lastIndex = lastIndex;
}
output.push(content.substring(lastIndex, content.length));
return output.join('');
}
这篇关于查找和替换为字典,仅使用键一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文