Reputation: 343
I am stuck with a problem that challenges me to create the regular expression for binary numbers (containing 0
s and 1
s). But the string should only match if the binary number only contains a maximum of five 1
s. How do I limit a character appearance in a regex?
Examples:
01101101
is correct01111100
is correct10110011
is correct01111110
is wrong11111110
is wrongUpvotes: 6
Views: 604
Reputation: 163207
If you engine supports lookaheads, and there can not be more than 8 times a 1 or 0 and the 1 should not occur more than 5 times, you might use:
^(?=[01]{8}$)(?!(?:0*1){6,})[01]+$
Explanation
^
Begin of the string(?=
Positive lookahead that asserts that what is on the right side
[01]{8}$
Match 8 times a 0 or 1 until the end of the string)
Close lookahead(?!
Negative lookahead that asserts that what is on the right side
(?:0*1){6,}
The pattern zero or more times a 0 followed by a 1 0*1
is not repeated 6 or more times (so 0 till 5 times is valid))
Close negative lookahead[01]+$
Match 0 or 1 one or more times$
The end of the stringUpvotes: 0
Reputation: 5213
^0*(?:10*){,5}$
Essentially this matches any combination of '1'
s and '0'
s but only allows a substring containing a single '1'
character to occur five times at most.
Try it out here: https://regex101.com/r/JKV1Uk/2
Explanation:
^
matches the beginning of the string
0*
matches zero or more '0'
s
(?:10*){,5}
matches up to 5 '1'
s followed by any number of zeros
$
matches the end of the string
Upvotes: 8