billyhalim25
billyhalim25

Reputation: 343

How do I limit a character appearance in a 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:

Upvotes: 6

Views: 604

Answers (2)

The fourth bird
The fourth bird

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 string

Upvotes: 0

bunji
bunji

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

Related Questions