G. Sena
G. Sena

Reputation: 429

Split a string while ignoring the char of the delimiter?

I am doing the split of the following string using the delimiter ' / ' The problem is that in the same string I have a ' - ' character that would like to remove it and what I have there after.

Input

var test = "This/ is /a - test";
 test.Split('/');

Output

test[0] = "This"
test[1] = "is"
test[2] = "a - test"

In test [2] it should be "a"

Upvotes: 0

Views: 1063

Answers (4)

andreim
andreim

Reputation: 3503

Regex solution based on an explicit capture of one group:

String myText = "This/ is /a normal - test/ and quite - another/ test";

Regex regex = new Regex(@"[/]?\s*(?<part>[^-/]+[^-/\s])[^/]*[/]?", RegexOptions.ExplicitCapture);

var strings = regex.Matches(myText).Cast<Match>().Select(match => match.Groups["part"].Value);

Console.WriteLine(strings.Aggregate((str1, str2) => str1 + ">" + str2));

This will yield:

This>is>a normal>and quite>test

Upvotes: 2

maccettura
maccettura

Reputation: 10818

First split the string on the - character. You said you wish to ignore everything after that so take the [0] index of the resulting array and perform your second string split on the that, splitting on: /

var test = "This/ is /a - test";
string[] hyphenSplit = test.Split('-');
string[] slashSplit = hyphenSplit[0].Split('/');

Upvotes: 3

Nicol&#225;s de Ory
Nicol&#225;s de Ory

Reputation: 622

Does this work for you?

var test = "This/ is /a - test";
var split1 = test.Split('-');
var split2 = split1[0].Split('/');

Basically what maccettura said.

Upvotes: 4

Terlan Abdullayev
Terlan Abdullayev

Reputation: 337

again split it for '-'

test[2] = test[2].Split('-')[0];

Upvotes: -1

Related Questions