如何获取所有字符串格式参数
有没有办法获取字符串的所有格式参数?
我有这个字符串:“{0} test {0} test2 {1} test3 {2:####}” 结果应该是一个列表: {0} {0} {1} {2:####}
.net 中是否有支持此功能的内置功能?
Is there a way to get all format parameters of a string?
I have this string: "{0} test {0} test2 {1} test3 {2:####}"
The result should be a list:
{0}
{0}
{1}
{2:####}
Is there any built in functionality in .net that supports this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我没有听说过这样的内置功能,但您可以尝试一下(我假设您的字符串包含以数字开头的标准格式参数):
它返回
{0} {0} {1} { 2:####}
列表中的值。对于 tehMick 的字符串,结果将是一个空集。I didn't hear about such a build-in functionality but you could try this (I'm assuming your string contains standard format parameters which start with number digit):
it returns
{0} {0} {1} {2:####}
values in the list. For tehMick's string the result will be an empty set.您可以使用正则表达式来查找与该模式匹配的所有子字符串。
像
\{.*?\}
这样的正则表达式可能就可以解决问题。You could use a regular expression to find all the substrings matching that pattern.
A regular expression like
\{.*?\}
would probably do the trick.不,没有内置功能可以执行此操作。你必须用正则表达式或其他东西来解析它们
no, there is no built in feature to do this. You'd have to parse them out with a regex or something
看起来不像。 Reflector 建议所有格式字符串解析都发生在 StringBuilder.AppendFormat(IFormatProvider, string, object[]) 内部。
It doesn't look like it. Reflector suggests all the format string parsing happens inside StringBuilder.AppendFormat(IFormatProvider, string, object[]).
为了找到所有大括号的良好起点,您应该查看 FormatWith 扩展方法。
To get a good starting point on finding all the curly braces you should take a look into the FormatWith extension method.