Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting on “,” but not “/,”

Question: How do I write an expression to split a string on ',' but not '/,'? Later I'll want to replace '/,' with ', '.

Details...

Delimiter: ','

Skip Char: '/'

Example input: "Mister,Bill,is,made,of/,clay"

I want to split this input into an array: {"Mister", "Bill", "is", "made", "of, clay"}

I know how to do this with a char prev, cur; and some indexers, but that seems beta.

Java Regex has a split functionality, but I don't know how to replicate this behavior in C#.

Note: This isn't a duplicate question, this is the same question but for a different language.

like image 553
visc Avatar asked Oct 10 '14 14:10

visc


4 Answers

I believe you're looking for a negative lookbehind:

var regex = new Regex("(?<!/),");
var result = regex.Split(str);

this will split str on all commas that are not preceded by a slash. If you want to keep the '/,' in the string then this will work for you.

Since you said that you wanted to split the string and later replace the '/,' with ', ', you'll want to do the above first then you can iterate over the result and replace the strings like so:

var replacedResult = result.Select(s => s.Replace("/,", ", ");
like image 165
Luke Willis Avatar answered Oct 19 '22 23:10

Luke Willis


string s = "Mister,Bill,is,made,of/,clay";
var  arr = s.Replace("/,"," ").Split(',');

result : {"Mister", "Bill", "is", "made", "of clay"}

like image 42
Ilya Avatar answered Oct 20 '22 00:10

Ilya


Using Regex:

var result = Regex.Split("Mister,Bill,is,made,of/,clay", "(?<=[^/]),");
like image 44
brz Avatar answered Oct 20 '22 00:10

brz


Just use a Replace to remove the commas from your string :

 s.Replace("/,", "//").Split(',').Select(x => x.Replace("//", ","));
like image 44
Seb Avatar answered Oct 19 '22 22:10

Seb