Douglas Anderson
Douglas Anderson

Reputation: 4710

match inside a match

I have a simple string:

data1:abc,123,xyz,data2:hello,goodbye

I need regex to return a match collection of:

abc
123
xyz

In the past I'd do it with a regular expression:

data1:(.*)data2:

and then split the output of that on the comma.

Is there a way to do this as one regular expression and no external code?

Upvotes: 2

Views: 180

Answers (2)

stema
stema

Reputation: 93026

Try this

String text = "data1:abc,123,xyz,data2:hello,goodbye";
Regex reg = new Regex(@"(?<=data1:.*)[^,]+(?=.*data2)");

MatchCollection result = reg.Matches(text);

foreach (var item in result) {
    Console.WriteLine(item.ToString());
}

output:

abc
123
xyz

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176936

Not sure but you can do soemthing like

String s="data1:abc,123,xyz,data2:hello,goodbye "
sttring[] slst= s.split(":");

for (int i = 0;i<slst.lemgth;i++)
{
 string[] inr = slst[i].split(",");
 for (int j = 0;j<inr.lemgth;j++)
 {
   if((inr.IndexOf("data") != -1)
    continue;
    //your code  
 }
} 

Upvotes: 1

Related Questions