tags:

views:

4065

answers:

3

i am having trouble splitting a string in c# with a delimiter of "][".

For example the string "abc][rfd][5][,][."

Should yield an array containing;
abc
rfd
5
,
.

But I cannot seem to get it to work, even if I try RegEx I cannot get a split on the delimiter.

EDIT: Essentially I wanted to resolve this issue without the need for a Regular Expression. The solution that I accept is;

string Delimiter = "][";  
var Result[] = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None);

I am glad to be able to resolve this split question.

+1  A: 
        string tests = "abc][rfd][5][,][.";
        string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);
SwDevMan81
Note that this approach assumes he means to split on every ] and [, even when they do not appear in the ][ combination.
Lasse V. Karlsen
That overload of string.Split is treating it as 2 separate delimiters - simply you are discarding the rest. There is an overload that accepts a string as a delimiter (actually, an array of strings) - so you don't have to remove the empty values (meaning also: you can **find** empty values when they validly exist in the data)
Marc Gravell
Your ] assumption is [ correct. He didnt specify, so I gave him something that would work for his example. If he doesnt want to skip them, then would work. But without more information, we'll never know
SwDevMan81
+12  A: 

To show both string.Split and Regex usage:

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");
Marc Gravell
A: 
Regex.Split("abc][rfd][5][,][.", @"\]\]");
codedevour
You probably want a `\[` in there somewhere...
Marc Gravell