crauscher
crauscher

Reputation: 6618

How to get all string format parameters

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?

Upvotes: 4

Views: 3785

Answers (5)

Oleks
Oleks

Reputation: 32333

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.

Upvotes: 4

Oliver
Oliver

Reputation: 45101

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

Upvotes: 0

Daniel Renshaw
Daniel Renshaw

Reputation: 34177

It doesn't look like it. Reflector suggests all the format string parsing happens inside StringBuilder.AppendFormat(IFormatProvider, string, object[]).

Upvotes: 1

Syntactic
Syntactic

Reputation: 10961

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

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

Upvotes: 3

Joel Martinez
Joel Martinez

Reputation: 47749

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

Upvotes: 1

Related Questions