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.
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.
In .NET Regex you can do it with negative assertions.(?<!/)/(?!/)
will work. Use Regex.Split
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With