Joshua
Joshua

Reputation: 6241

Create String.Format like string and extract sub string

First of all, I want extract sub-string from string between delimiters into parameters and make the string become like a string for String.Format.

Example

Source:

<Hello> [World]!

Output:

Result string

<{0}> [{1}]!

Extracted parameters in array

0: Hello
1: World

There are lots of strings which contains an unknown amount of parameter. Also, there are two types of delimiter: <> and [].

I searched for string extraction example using regex but most of them are base on a static string format. However, the format of string is unknown and may or may not be contain any delimiters in this case.

Edit: There is a possibility delimiter wrap by other delimiters but delimiter will always come in pair.

Example

Source:

[<Hello> World]!

Output:

Result string

[{0}]!

Extracted parameters in array

0: <Hello> World

Only outer delimiter will be considered. Anything inside should be parameters.

Upvotes: 1

Views: 179

Answers (1)

Reddog
Reddog

Reputation: 15579

You could try using a Regex to parse out matching sets of <> and []. Then you use a regex replace with a custom MatchEvaluator

Something like this might work:

var regex = new Regex(@"(?<=\<).*(?=\>)|(?<=\[).*(?=\])");
var input = "<Hello> [World]!";
var index = 0;
var replacements = new List<string>();
var formatString = regex.Replace(input, (m) => 
{
    replacements.Add(m.Value);
    return String.Format("{{{0}}}", index++);
});

I haven't really dealt with input strings that contain <>[] but you could make up and escaping pattern and deal with it. The original regex was based on this answer.

Edit: Here's a .NET Fiddle for it...

Upvotes: 3

Related Questions