Best way to embed data fields in text?
What's the best way to embed data fields in text so they are easily retrievable, and don't affect readability (much)?
For instance, I could do something like "Some instructions here, followed by @firstname:John @lastname:Smith\n", and then write code to parse out the fields. Then I could begin to work out the problems, like embedded @-signs.
But this has been done so many thousands of ti开发者_JS百科mes, I'm hoping someone can point me to a settled pattern.
Gonna wager a guess based on your question, let me know if I misunderstood...
You'll want to go with something that can easily be picked up by regular expressions and/or variable replacement. It should also be characters you don't use frequently in your text.
Something like "Hello ${firstName} how are you doing today?", or more simply "Hello {0} what's up?"
Some languages have built in support for this, so it depends on your environment.
As Mike said it depends on the environment. In .NET you have "Hello {0}", several languages uses "Hello %s", JavaScript using MooTools uses "Hello {name}" and so on, and so on. Both the "{0}" and "%s" depends on the order of the arguments (which might be a disadvantage).
If you're interested in how to implement it by yourself here is an example using regular expressions in javascript:
// Variables should be an object at the current form:
// {name: 'John', age: 13}
function substitute(string, variables)
{
var result = string.replace(/\\?\{([^{}]+)\}/g, function(match, name) {
if(match.charAt(0) == '\\') return match.slice(1); //If there was a backslash before the first {, just return it as it was.
return (variables[name] != undefined) ? variables[name] : '';
});
return result;
}
It shouldn't bee to hard porting to other languages which support regular expressions.
Perhaps a bit of a hack, but if this is just a simple requirement to format some text for a message or internationalisation (etc) you could abuse String.format() (in java, presumably those windows languages have something similar), which takes either a varargs or array parameter like this:
String text = "Hello %s, do you still live at %s?";
String[] replacements = {
user.name(),
user.address()
};
String formatted = String.format(text, replacements);
The only problem of course is you cant specify in this the order of the parameters, just where they appear. That may or may not be a problem, but this is probably the quickest solution if it's not.
精彩评论