I am stuck with a problem that challenges me to create the regular expression for binary numbers (containing 0s and 1s). But the string should only match if the binary number only contains a maximum of five 1s. How do I limit a character appearance in a regex?
Examples:
01101101 is correct01111100 is correct10110011 is correct01111110 is wrong11111110 is wrong^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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With