I am trying to split a string in C# the following way:
Incoming string is in the form
string str = \"[message details in here][another message here]/
The Split method returns sub strings between the instances of the pattern specified. For example:
var items = Regex.Split("this is a test", @"\s");
Results in the array [ "this", "is", "a", "test" ]
.
The solution is to use Matches instead.
var matches = Regex.Matches(str, @"\[[^[]+\]");
You can then use Linq to easily get an array of matched values:
var split = matches.Cast<Match>()
.Select(m => m.Value)
.ToArray();
Use the Regex.Matches
method instead:
string[] result =
Regex.Matches(str, @"\[.*?\]").Cast<Match>().Select(m => m.Value).ToArray();
Instead of using a regex you could use the Split
method on the string like so
Split(new[] { '\n', '[', ']' }, StringSplitOptions.RemoveEmptyEntries)
You'll loose [
and ]
around your results with this method but it's not hard to add them back in as needed.
Another option would be to use lookaround assertions for your splitting.
e.g.
string[] split = Regex.Split(str, @"(?<=\])(?=\[)");
This approach effectively splits on the void between a closing and opening square bracket.