Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a string e.g. School name is {SchoolName} and school contact number is {SchoolPhone} and email is {SchoolEmail}

i want to find all the tags wrapped in {} and put them in collection or string array. How to do this?
Posted

use Regular expression to match the pattern {}.
 
Share this answer
 
Comments
xpertzgurtej 27-Mar-15 2:12am    
thanks for the reply but i have to find all the tags wrapped in {} not just the {}. Please reply with suitable example if possible
Use some of standard string commands -
string.subString[^]
string.indexOf[^]
string.split[^]
 
Share this answer
 
Comments
xpertzgurtej 27-Mar-15 2:13am    
thanks for the reply. But can you please provide suitable example to achieve my requirement?
C#
var givenString =
                "School name is {SchoolName} and school contact number is {SchoolPhone} and email is {SchoolEmail}";
            const string START_CHAR = "{";
            const string END_CHAR = "}";
         var result=new List<string>();
         while (givenString.IndexOf(START_CHAR, System.StringComparison.Ordinal) > -1)
            {
                var startIndex = givenString.IndexOf(START_CHAR, 
             System.StringComparison.Ordinal);
                var endIndex = givenString.IndexOf(END_CHAR, 
                System.StringComparison.Ordinal);

                result.Add(givenString.Substring(startIndex + 1,endIndex-startIndex-1));
                givenString = givenString.Substring(endIndex+1);
            }
 
Share this answer
 
C#
{[@a-zA-Z0-9-]*}

will catch all what is inside curly brackets
and is a combination of lower case letters, upper case letters, numbers, dashes and at signs.
 
Share this answer
 
Hi, here is straightforward solution for you:
C#
string input = "School name is {SchoolName} and school contact number is {SchoolPhone} and email is {SchoolEmail}";

string[] output = Regex.Matches(input, "{[^{}]*}")
                       .OfType<Match>()
                       .Select(match => match.Value)
                       .ToArray();

The Regex pattern that I used will match everything that begins with '{' and ends with '}' and does not contain those two characters inside of it.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900