给定一个包含替换键的字符串,我如何才能最有效地使用 Java 将这些键替换为运行时值?我需要经常、快速地在相当长的字符串(例如,平均 1-2kb)上执行此操作。键的形式是我的选择,因为我也在此处提供了模板。
这是一个示例(请不要执着于它是 XML;如果可能的话,我想这样做比使用 XSL 或 DOM 操作更便宜)。我想用 bean 属性、真正的 Property
属性和其他一些来源的属性值替换其中的所有 @[^@]*?@
模式。这里的关键是快。有什么想法吗?
<?xml version="1.0" encoding="utf-8"?>
<envelope version="2.3">
<delivery_instructions>
<delivery_channel>
<channel_type>@CHANNEL_TYPE@</channel_type>
</delivery_channel>
<delivery_envelope>
<chan_delivery_envelope>
<queue_name>@ADDRESS@</queue_name>
</chan_delivery_envelope>
</delivery_envelope>
</delivery_instructions>
<composition_instructions>
<mime_part content_type="application/xml">
<content><external_uri>@URI@</external_uri></content>
</mime_part>
</composition_instructions>
</envelope>
天真的实现是使用 String.replaceAll()
但我不禁认为这不太理想。如果我能避免添加新的第三方依赖项,那就更好了。
最佳答案
Matcher 中的 appendReplacement 方法看起来它可能很有用,尽管我不能保证它的速度。
这是来自 Javadoc 的示例代码:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
编辑:如果这变得如此复杂,您可能可以相当轻松地实现自己的状态机。您几乎可以做 appendReplacement 已经在做的事情,尽管专门的实现可能会更快。
关于java - 我需要一个用于 Java 的快速 key 替换算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/463460/