Given a string with replacement keys in it, how can I most efficiently replace these keys with runtime values, using Java? I need to do this often, fast, and on reasonably long strings (say, on average, 1-2kb). The form of the keys is my choice, since I’m providing the templates here too.
Here’s an example (please don’t get hung up on it being XML; I want to do this, if possible, cheaper than using XSL or DOM operations). I’d want to replace all @[^@]*?@ patterns in this with property values from bean properties, true Property properties, and some other sources. The key here is fast. Any ideas?
<?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>
The naive implementation is to use String.replaceAll() but I can’t help but think that’s less than ideal. If I can avoid adding new third-party dependencies, so much the better.
The appendReplacement method in Matcher looks like it might be useful, although I can’t vouch for its speed.
Here’s the sample code from the Javadoc:
EDIT: If this is as complicated as it gets, you could probably implement your own state machine fairly easily. You’d pretty much be doing what appendReplacement is already doing, although a specialized implementation might be faster.