Exact number of times a given character must repeat Regex

Asked

Viewed 327 times

3

Hello, I’m with an exercise in formal languages, of which we work with Regex, the exercise consists in validating a chain that has exactly four 1s, for example:

chain 1: 0110101000 - valid;

jail 2: 010110 - invalid;

chain 3: 011011011 - invalid;

What I’ve been able to do so far is validate a string with four or more 1s, but I haven’t been able to determine exactly the number of times a given character should repeat:

Follows the expression I’ve managed to develop so far: /(\S*1){4}.*/

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

Thanks in advance!!

2 answers

2

  • 1

    Thank you very much friend, both answers worked the way I needed them.

2


The other characters can only be zeros, or they can be anything other than 1?


Anyway, I’m using the expression [^1] (everything that is not 1) together with ^ (string start) and $ (end of string), to indicate that regex has to check the whole string, from start to finish:

/^([^1]*1[^1]*){4}$/

Explaining:

  • [^1]* - zero or more occurrences of anything other than 1 (to check what comes before the first 1)
  • 1 - own 1
  • [^1]* - zero or more occurrences of anything other than 1 (again, but here is to check what comes after the last 1)
  • The quantifier {4} says the previous expression (everything in parentheses: ([^1]*1[^1]*)) can only be repeated four times

Watch it work here.


Another option (since the question has the tag ) is to count the number of occurrences of the character 1, using match:

// conta a quantidade de "1" na string
var quantidadeDeUm = ("01001001001".match(/1/g) || []).length;

console.log(quantidadeDeUm); // 4

Then just check if the quantity is 4. The advantage is that the regex is much simpler, and in my opinion, it is a much easier code to understand and maintain.

The excerpt || [] returns an empty array, in case the match do not find any occurrence. I did this because when there is no occurrence, the match returns null, then in this case I use an empty array not to give a Typeerror: null.

  • 1

    Very good thanks for the quick response, both options have well met my need, thanks for the support!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.