最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Split string by char, but skip certain char combinations - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Feb 27, 2013 at 9:40 Adrian MarinicaAdrian Marinica 2,2015 gold badges30 silver badges54 bronze badges 1
  • 1 need to write custom logic , i don't think there is inbuilt mechanism to it AFAIK – TalentTuner Commented Feb 27, 2013 at 9:43
Add a comment  | 

4 Answers 4

Reset to default 10

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.

ok one thing you can do is to split the string based on /. The array you get back will contain empty allocations for all the places // were used. loop through the array and concatenate i-1 and i+1 allocations where i is the pointer to the empty allocation.

How about this:

var array = "First/Second//Third/Fourth".replace("//", "%%").split("/");

array.forEach(function(element, index) {
    array[index] = element.replace("%%", "//");
});
发布评论

评论列表(0)

  1. 暂无评论