enricco
enricco

Reputation:

string.split - by multiple character delimiter

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.

Upvotes: 200

Views: 306555

Answers (6)

Bob2Chiv
Bob2Chiv

Reputation: 1968

In .NETCore 2.0 and beyond, there is a Split overload that allows this:

string delimiter = "][";
var results = stringToSplit.Split(delimiter);

Split (netcore 2.0 version)

Upvotes: 1

Marco Concas
Marco Concas

Reputation: 1892

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

Upvotes: 0

SwDevMan81
SwDevMan81

Reputation: 49978

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 57

seabass2020
seabass2020

Reputation: 1123

Another option:

Replace the string delimiter with a single character, then split on that character.

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');

Upvotes: 28

Christopher Klewes
Christopher Klewes

Reputation: 11435

Regex.Split("abc][rfd][5][,][.", @"\]\]");

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062510

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, @"\]\[");

Upvotes: 316

Related Questions