2

I'm trying to split a string of binary digits in a specific way

Let's say this is my string 100011001110010101110

I want to split the string at every 0 before a 1

So the string above after split becomes

1000 1100 11100 10 10 1110

I used the Regex pattern /(1+0+)/g which splits the string properly, but it misses some groups. Here is the c# code

Regex.Split(stringToSplit, @"(1+0+)");

Please what am i getting wrong.

EDIT: I failed to mention that I am certain a 1 will always precede a 0

Thanks in advance.

3 Answers 3

6

You can try looking ahead and behind, i.e. spilt on zero-length text with 0 behind the split and 1 ahead it

Code:

  string source = "100011001110010101110";

  var result = Regex.Split(source, "(?<=0)(?=1)");

  // Let's have a look
  Console.Write(string.Join(Environment.NewLine, result));

Outcome:

1000
1100
11100
10
10
1110

Edit: Pattern (?<=0)(?=1) explanation:

(?<=0) - 0 should be behind the split
       - empty; split on epmty (zero-length) text
(?=1)  - 1 should be ahead of the split

So we have

1000 110011
   ^^^
   |||- 1 should be ahead of split
   ||--   split here
   |--- 0 should be behind the split
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Can you please add more explanation about the pattern?
This works like a charm. No extra processing, you get the exact results you need.
1

Problem is your Regex Pattern returns several Matches as you can see Here.

You could retrieve the values using .Matches() instead.

Regex.Matches("100011001110010101110", "(1+0+)").Cast<Match>().Select(x => x.Value);

2 Comments

You will lose any leading zeros or trailing ones if present.
This works but it seems the Cast and Select increases execution time. Thanks for the response.
0

Code:

var input = "100011001110010101110";
var results = Regex.Split(input, @"(1+0+)")
                        .Where(n => !string.IsNullOrEmpty(n))
                        .ToList();
Console.WriteLine(string.Join("\n", results));

Outcome:

1000
1100
11100
10
10
1110
Press any key to continue . . .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.