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 javascript) 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.
Thank you very much friend, both answers worked the way I needed them.
– Jefferson Bruchado