Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit a character appearance in a regex?

Tags:

regex

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 correct
  • 01111100 is correct
  • 10110011 is correct
  • 01111110 is wrong
  • 11111110 is wrong
like image 682
billyhalim25 Avatar asked Mar 07 '23 14:03

billyhalim25


1 Answers

^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

like image 95
bunji Avatar answered Mar 10 '23 10:03

bunji