jsg
jsg

Reputation: 1264

c# extracting a certain value within a string

I'm trying to remove a certain bit of text within a string.

Say the string I have contains html elements, like paragraph tags, I created some sort of tokens that will be identified with "{" at the beginning and "}" at the end.

So essentially the string I have would look like this:

text = "<p>{token}</p><p> text goes here  {token3}</p>"

I'm wondering is there a way to extract all the words including the "{}" using C#-Code within the string.

Whilst each token could be different to the next, that is why i must use "{" and "}" to identify them as seen below

At the moment I'm got to this code:

var newWord = text.Contains("{") && word.Contains("}")

Upvotes: 0

Views: 372

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

Something like

var r = new Regex("({.*?})");
foreach(var match in r.Matches(myString)) ...

The ? means that your regex is non-greedy. If you omit it you´ll simply get everythinbg between the first { and the last }.

Alternativly you may also use this:

var index = text.IndexOf("{");
while (index != -1)
{
    var end = text.IndexOf("}", index);
    result.Add(text.Substring(index, end - index + 1));
    index = text.IndexOf("{", index + 1);
}

Upvotes: 3

Alexander Derck
Alexander Derck

Reputation: 14498

I would just use a regex for this:

Regex reg = new Regex("{.*?}");

var results = reg.Matches(text);

The regex searches for any characters between { and }. The .*? means match any character but in a non greedy way. So it will search for the shortest possible string between braces.

Upvotes: 2

Related Questions