4

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
billyhalim25
  • 183
  • 1
  • 1
  • 13

2 Answers2

7
^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

Ronan Boiteau
  • 8,035
  • 6
  • 32
  • 47
bunji
  • 4,366
  • 14
  • 29
  • Thanks for your answer. However, `^0*(10*){0,5}$` also works. So I want to ask what are the functions of `?` and `:` there? – billyhalim25 Mar 25 '18 at 15:33
  • 1
    The `?:` makes a group [non-capturing](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-what-does-do). From your description it didn't seem like you needed to capture any groups so I made it non-capturing out of habit since there is a [slight cost](https://stackoverflow.com/questions/41444807/why-is-regex-search-slower-with-capturing-groups-in-python) to using capturing groups with most regex engines. You are right though, it works either way. – bunji Mar 25 '18 at 17:54
0

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 string
The fourth bird
  • 96,715
  • 14
  • 35
  • 52