如何获取所有字符串格式参数

发布于 2024-08-30 02:44:26 字数 143 浏览 2 评论 0原文

有没有办法获取字符串的所有格式参数?

我有这个字符串:“{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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

风轻花落早 2024-09-06 02:44:26

我没有听说过这样的内置功能,但您可以尝试一下(我假设您的字符串包含以数字开头的标准格式参数):

List<string> result = new List<string>();
string input = "{0} test {0} test2 {1} test3 {2:####}";
MatchCollection matches = Regex.Matches(input, @"\{\d+[^\{\}]*\}");
foreach (Match match in matches)
{
    result.Add(match.Value);
}

它返回 {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):

List<string> result = new List<string>();
string input = "{0} test {0} test2 {1} test3 {2:####}";
MatchCollection matches = Regex.Matches(input, @"\{\d+[^\{\}]*\}");
foreach (Match match in matches)
{
    result.Add(match.Value);
}

it returns {0} {0} {1} {2:####} values in the list. For tehMick's string the result will be an empty set.

暗藏城府 2024-09-06 02:44:26

您可以使用正则表达式来查找与该模式匹配的所有子字符串。

\{.*?\} 这样的正则表达式可能就可以解决问题。

You could use a regular expression to find all the substrings matching that pattern.

A regular expression like \{.*?\} would probably do the trick.

探春 2024-09-06 02:44:26

不,没有内置功能可以执行此操作。你必须用正则表达式或其他东西来解析它们

no, there is no built in feature to do this. You'd have to parse them out with a regex or something

神仙妹妹 2024-09-06 02:44:26

看起来不像。 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[]).

愛放△進行李 2024-09-06 02:44:26

为了找到所有大括号的良好起点,您应该查看 FormatWith 扩展方法

To get a good starting point on finding all the curly braces you should take a look into the FormatWith extension method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文