Reputation: 3
I'm working to create a regex to match a binaries with an even number of zeros.
For example, it should match numbers like:
001
1010
100100
But it shouldn't match:
0010
10001
00101
This is what I have so far:
(([0]{1})+)
I will really highly appreciate any help on this.
Upvotes: 0
Views: 310
Reputation: 147156
Although not the best way, you can use a regex for this, searching for pairs of 0
's in the string and asserting that there are no other 0
characters in the string outside those pairs (thus there must be an even number of 0
's):
^(?:[^0]*0[^0]*0)+[^0]*$
const strs = [
'1010',
'100100',
'0010',
'10001',
'00101',
'001',
'1001',
'100',
'101'
]
strs.map(s => console.log(s + ': ' + /^(?:[^0]*0[^0]*0)+[^0]*$/.test(s)));
Upvotes: 1