user2739591
user2739591

Reputation: 45

Regex to match binary numbers with more than two set bits

If I have a number consisting only of 1's and 0's and I need to create a regular expression that will match only if said number contains more than two instances of the digit 1.

Some examples:

1000000010001
0001100000000
1000110010000
0000001000000
0100010000000

I'd need my expression to correctly match the 1st and 3th examples.

I'm guessing this should be some basic stuff. The best I managed was:

1.+1.+(1)

It's giving me some problems though, so I'd like to know if there's a better way to go about this.

Upvotes: 2

Views: 951

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can simply use:

.*1.*1.*1.*

regex101 doodle

So three 1's with .* in between. The Kleene star means zero or more repetitions whereas the .+ means one or more repetitions.

The first and last .* are not required if you don't use start (^) and end anchors $. Otherwise these are: ^.*1.*1.*1.*$.

Or in case - as @Kasra says - it is not guaranteed that the string contains only ones and zeros, you can use the regex:

10*10*1

To match the fragments or lines with grep. Or to match the full line:

^[0-1]*10*10*1[0-1]*$

Upvotes: 3

karthik manchala
karthik manchala

Reputation: 13640

You can use the following:

^0*10*10*1[10]*$

Which is equivalent to:

^(?:0*1){3}[10]*$

See DEMO

Upvotes: 2

Cu3PO42
Cu3PO42

Reputation: 1473

What you did was pretty good. I changed it up a little bit to match the complete number and accommodate all possible cases:

((?:0*1){3,}0*)

See an example here.

This is, of course assuming you only have binary numbers. If not, feel free to change up the 0 to [02-9] to include all other digits, too.

Breakdown

(?:0*1) matched any number of 0 and then one 1. {3,} means to find this group at least three times, this means there have to be at least three, i.e. more than two, 1. Then we match any number of 0s in case the number does not end in a 1 and to include the whole number in the match.

Upvotes: 3

Related Questions