在文本中嵌入数据字段的最佳方式?
在文本中嵌入数据字段的最佳方法是什么,以便它们可以轻松检索,并且不会(太大)影响可读性?
例如,我可以做类似的事情 “这里有一些说明,后面是@firstname:John @lastname:Smith\n”,然后编写代码来解析字段。然后我就可以开始解决问题,比如嵌入的@符号。
但这已经完成了数千次,我希望有人能指出我一个固定的模式。
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 times, I'm hoping someone can point me to a settled pattern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将根据您的问题进行猜测,如果我误解了,请告诉我...
您会想要使用可以通过正则表达式和/或变量替换轻松获取的内容。它还应该是您在文本中不经常使用的字符。
类似于“Hello ${firstName},你今天过得怎么样?”,或者更简单地说“Hello {0},最近怎么样?”
有些语言内置了对此的支持,因此这取决于您的环境。
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.
正如迈克所说,这取决于环境。在 .NET 中,有“Hello {0}”,多种语言使用“Hello %s”,使用 MooTools 的 JavaScript 使用“Hello {name}”等等。 “{0}”和“%s”都取决于参数的顺序(这可能是一个缺点)。
如果您对如何自己实现它感兴趣,这里有一个在 javascript 中使用正则表达式的示例:
不应该硬移植到支持正则表达式的其他语言。
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:
It shouldn't bee to hard porting to other languages which support regular expressions.
也许有点黑客,但如果这只是格式化消息或国际化等的一些文本的简单要求,您可以滥用 String.format() (在 java 中,大概那些 Windows 语言也有类似的东西),这需要可变参数或数组参数,如下所示:
当然,唯一的问题是您无法在此指定参数的顺序,仅指定它们出现的位置。这可能是问题,也可能不是问题,但如果不是问题,这可能是最快的解决方案。
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:
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.