stackers
stackers

Reputation: 3270

Regex group by finding one of two repeating groups

I want to sort this into groups of 1s and groups of zeros

    var string = '10011110000100101';

    var matches = string.match(/0*|1*/gi);

    console.log(matches);

I currently get

 ["", "00", "", "", "", "", "0000", "", "00", "", "0", "", ""]

Expected output:

 ["1", "00", "1111", "0000", "1", "00", "1", "0", "1"]

The 1s aren't being grouped, and are showing up blank.

If I switch the one and zero, the opposite happens:

["1", "", "", "1111", "", "", "", "", "1", "", "", "1", "", "1", ""]

Upvotes: 0

Views: 39

Answers (2)

Amal Murali
Amal Murali

Reputation: 76656

You're using the * quantifier for both 0 and 1. * means "match the preceding token zero or more times". The regex matches an empty string, and that's reflected in your final output. To fix this, you can use +, which means "match the preceding token one more times".

/(0+|1+)/

RegEx Demo

Upvotes: 2

Pointy
Pointy

Reputation: 413717

Use + instead of *:

   var matches = string.match(/0+|1+/gi);

The problem is that 0* matches a 1 in the string.

Upvotes: 1

Related Questions