ravikiran
ravikiran

Reputation: 1347

how to obtain substrings those are within the angular brackets in a string

i think this would be really silly question , but iam not succesful with extratic srtings those within the angular barkets in a sentence .

var str = "MR. {Name} of {Department} department stood first in {Subjectname}"

i need to obtain the substrings (as array) those are within the angular brakets

like strArray should contain {Name,Department,Subjectname} from the above given string

Upvotes: 5

Views: 482

Answers (3)

Binoj Antony
Binoj Antony

Reputation: 16196

Noting the use of var in your question, I will assume that you are using .NET 3.5.
The one line of code below should do the trick.

string[] result = Regex.Matches(str, @"\{([^\}]*)\}").Cast<Match>().Select(o => o.Value).ToArray();

Upvotes: 8

CRice
CRice

Reputation: 12567

Use String.IndexOf("{") to get the index of the first open tag and String.IndexOf("}") to get the index of the first close tag. Then use the other string functions to get it out (substring, remove etc)...while there are still tags

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063393

    List<string> fields = new List<string>();
    foreach(Match match in Regex.Matches(str, @"\{([^\}]*)\}")) {
        fields.Add(match.Groups[1].Value);
    }

Or for formatting (filling in the blanks) - see this example.

Upvotes: 6

Related Questions