Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenates Regex.Matches to a string

This is my first question on Stack I have a string like this

string str = "key1=1;main.key=go1;main.test=go2;key2=2;x=y;main.go23=go23;main.go24=test24";

the matches pattern applied to extract all strings that starts with main. returns the

Regex regex = new Regex("main.[^=]+=[^=;]+");       
MatchCollection matchCollection = regex.Matches(str);

I have tried this to concatenates the match collection

string flatchain = string.Empty;
foreach (Match m in matchCollection)
{
    flatchain = flatchain +";"+ m.Value; 
}

Is there any better way to do it using LINQ ?

like image 742
200 L.B Avatar asked Feb 02 '14 11:02

200 L.B


1 Answers

You can try to convert your result into an array and apply the string.Join to put your string in flat here you must specify the Match type explicitly as the MatchCollection is a non-generic IEnumerable type

  var toarray = from Match match in matchCollection select match.Value;
                string newflatChain = string.Join(";", toarray); 

or if you want just one line you can do it like the following

string newflatChain = string.Join(";", from Match match in matchCollection select match.Value);
like image 105
BRAHIM Kamel Avatar answered Sep 30 '22 02:09

BRAHIM Kamel