CodeLover
CodeLover

Reputation: 281

What will be the regex that not accept 0-0-0?

I want to write regex that can accept the following points,

1-The format should be x-y-z

2-x,y and z should be numbers.

3- x can be any number.

4-y can not be exceeded from 20.

  1. z can not be exceeded from 272.

6- x,y,z can not be 0 at the same time.

I wrote a regex that fulfilled the first 5 points. The regex is

^([0-9]+)-([0-9]|1[0-9])-([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-6][0-9]|27[0-2])$ 

But it also accept the 0-0-0 which should not be accepted. Is there any way to avoid 0-0-0?

Upvotes: 1

Views: 195

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You can add a (?!0+-0+-0+$) negative lookahead at the start right after the ^ to anchor it:

^(?!0+-0+-0+$)([0-9]+)-([0-9]|1[0-9])-([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-6][0-9]‌​|27[0-2])$

See the regex demo

The (?!0+-0+-0+$) will fail a match if the whole string only contains 0s and -s.

var re = /^(?!0+-0+-0+$)([0-9]+)-([0-9]|1[0-9])-([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-6][0-9]‌​|27[0-2])$/; 
var strs = ['1-19-44', '0-0-0', '0-0-6'];
for (var s of strs) {
  document.body.innerHTML += s + ": <b>" + re.test(s) + "</b><br/>";
}

Upvotes: 4

Related Questions