0

I have an exercise in formal languages, of which we work with Regex, the exercise is to validate a chain that has exactly four 1s, for example:

chain 1: 0110101000 - valid;

chain 2: 010110 - invalid;

chain 3: 011011011 - invalid;

What I've been able to do so far has been to validate a string with four or more 1s, but I have not been able to determine exactly how many times a given character should repeat:

Here is the expression that I have been able to develop so far: /(\S*1){4}.*/

This expression validates strings longer than four 1s, I need to validate a string that has exactly four 1s.

Thank you very much in advance!!

Jefferson Bruchado
  • 888
  • 2
  • 14
  • 33
  • 2
    Try `^[^1]*(1[^1]*){4}$`. Anchors at both ends are necessary. I'm sure this question has been asked many times before. I'll mark this as a dupe. – revo Jul 25 '18 at 14:04

1 Answers1

2

You may use

^(?:0*1){4}0*$

See the regex demo

The scheme is: ^(?:<ALL_BUT_ONE>*<ONE>){<LIMIT_NUM>}<ALL_BUT_ONE>*$

The pattern means

  • ^ - start of string
  • (?:0*1){4} - 4 repetitions of a sequence of patterns
    • 0* - zero or more 0 chars
    • 1 - a 1 char
  • 0* - zero or more (*) 0 chars
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563