Splitting String

G

Guadala Harry

I have a string that must be split out into a string array.

The segment delimiter is like this: {flag:xxx} and the "xxx" part is unknown
ahead of time (can be just about any character AND any number of characters
(at least one).
Here is a valid sample:
string sStartWithThis = "this goes to element one {flag:x} this goes to
element 2 {flag:pxedqr} this goes to element 3 {flag:pzf} this goes to
element 4.

How can I parse this string into an array of 4 elements? (none include the
{flag:...} delimiter).

Thanks!
 
W

William Stacey [MVP]

string s = @"this goes to element one {flag:x} this goes to element 2
{flag:pxedqr} this goes to element 3 {flag:pzf} this goes to element 4.";
string[] sa = Split(s);
foreach(string ts in sa)
{
Console.WriteLine(ts);
}

public static string[] Split(string inString)
{
Regex r = new Regex("({flag:.+?})"); // Split on hyphens.
string[] sa = r.Split(inString);
for(int i=0; i< sa.Length; i++)
{
sa = sa.Trim();
}
return sa;
}

If you don't want the "{flag:xxx}" delimiter in the result array, remove the
group "( )" parens in the Regex string.
So Regex("({flag:.+?})") would become Regex("{flag:.+?}") to give you this
output for above code:

this goes to element one
this goes to element 2
this goes to element 3
this goes to element 4.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top