我的输入就像"Hi {{username}}"
,即。带有要替换的关键字的字符串。但是,输入的值很小(〜10个关键字,总共1000个字符),我在哈希表数据结构中存储了100万个可能的关键字,每个关键字都与其替换相关联。
因此,出于明显的性能原因,我不想遍历关键字列表并尝试替换输入中的每个关键字。我更喜欢通过查找正则表达式模式对输入字符进行一次迭代"\{\{.+?\}\}"
。
在Java中,我使用Matcher.appendReplacement
和Matcher.appendTail
方法来实现。但是我找不到与相似的API NSRegularExpression
。
private String replaceKeywords(String input)
{
Matcher m = Pattern.compile("\\{\\{(.+?)\\}\\}").matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find())
{
String replacement = getReplacement(m.group(1));
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
return sb.toString();
}
我是否被迫自己实现此类API,还是错过了某些东西?
您可以使用以下方法实现此目的NSRegularExpression
:
NSString *original = @"Hi {{username}} ... {{foo}}";
NSDictionary *replacementDict = @{@"username": @"Peter", @"foo": @"bar"};
NSString *pattern = @"\\{\\{(.+?)\\}\\}";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSMutableString *replaced = [original mutableCopy];
__block NSInteger offset = 0;
[regex enumerateMatchesInString:original
options:0
range:NSMakeRange(0, original.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange range1 = [result rangeAtIndex:1]; // range of the matched subgroup
NSString *key = [original substringWithRange:range1];
NSString *value = replacementDict[key];
if (value != nil) {
NSRange range = [result range]; // range of the matched pattern
// Update location according to previous modifications:
range.location += offset;
[replaced replaceCharactersInRange:range withString:value];
offset += value.length - range.length; // Update offset
}
}];
NSLog(@"%@", replaced);
// Output: Hi Peter ... bar
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句