Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by char, but skip certain char combinations

Say I have a string in a form similar to this:

"First/Second//Third/Fourth" (notice the double slash between Second and Third)

I want to be able to split this string into the following substrings "First", "Second//Third", "Fourth". Basically, what I want is to split the string by a char (in this case /), but not by double of that char (in this case //). I though of this in a number of ways, but couldn't get it working.

I can use a solution in C# and/or JavaScript.

Thanks!

Edit: I would like a simple solution. I have already thought of parsing the string char by char, but that is too complicated in my real live usage.

like image 686
Adrian Marinica Avatar asked Nov 30 '22 04:11

Adrian Marinica


2 Answers

Try with this C# solution, it uses positive lookbehind and positive lookahead:

        string s = @"First/Second//Third/Fourth";
        var values = Regex.Split(s, @"(?<=[^/])/(?=[^/])", RegexOptions.None);

It says: delimiter is / which is preceded by any character except / and followed by any character except /.

Here is another, shorter, version that uses negative lookbehind and lookahead:

        var values = Regex.Split(s, @"(?<!/)/(?!/)", RegexOptions.None);

This says: delimiter is / which is not preceded by / and not followed by /

You can find out more about 'lookarounds' here.

like image 98
Ivan Golović Avatar answered Dec 04 '22 15:12

Ivan Golović


In .NET Regex you can do it with negative assertions.(?<!/)/(?!/) will work. Use Regex.Split method.

like image 41
RoadBump Avatar answered Dec 04 '22 15:12

RoadBump