How to limit the appearance of a character in a regular expression?

I am stuck with a problem that challenges me to create a regex for binary numbers (containing 0and 1s). But the string should only match if the binary number contains a maximum of five 1s. How to limit the appearance of a character in a regular expression?

Examples:

  • 01101101 correct
  • 01111100 correct
  • 10110011 correct
  • 01111110 wrong
  • 11111110 wrong
+4
source share
2 answers
^0*(?:10*){,5}$

Essentially, this matches any combination '1'and '0', but assumes that a substring containing a single character '1'will be executed a maximum of five times.

Try it here: https://regex101.com/r/JKV1Uk/2

Explanation:

  • ^ matches the beginning of a line

  • 0* '0' s

  • (?:10*){,5} 5 '1',

  • $

+7

lookaheads 8 1 0, 1 5 , :

^(?=[01]{8}$)(?!(?:0*1){6,})[01]+$

  • ^
  • (?= , , ,
    • [01]{8}$ 8 0 1
  • )
  • (?! , ,
    • (?:0*1){6,} a 0, 1 0*1, 6 ( 0 5 )
  • )
  • [01]+$ 0 1
  • $
0

Source: https://habr.com/ru/post/1695294/


All Articles