Pratyaksh Chaudhary - 6 months ago 39

Javascript Question

I am trying to create a regex which matches 7-15 digit number, the number cannot contain all the same digits and Last 7 digits cannot be the same. I have made two regex expressions for number that all numbers cannot be same. The regex which I have made is:

`/^(?!(.)\1+$)^(|[0-9]{7,15})$/`

And for Last seven digits cannot be same,the regex which i have made is:

`/^(?!.*(\d)\1{6}\b)^[0-9]{0,15}$/`

But the problem is I am not able to make the regex which full fills both the conditions i.e. all the numbers cannot contain all the same digits and Last 7 digits cannot be the same.

Please suggest how this can be done.

Answer

It seems you can use alternation operator inside the negative lookahead to check for 2 conditions:

```
^(?!(\d)\1+$|\d*(\d)\2{6}$)(?:\d{7,15})?$
```

See the regex demo.

**Details**:

`^`

- start of string`(?!(\d)\1+$|\d*(\d)\2{6}$)`

- the negative lookahead failing the match if all digits are the same from start to end (`(\d)\1+$`

where`(\d)`

captures a digit into Group 1 and then`\1+`

matches one or more values captured in Group 1 followed with end of string check with`$`

), or if only the last 7 are the same (see`\d*(\d)\2{6}$`

where`\d*`

matches 0+ digits,`(\d)`

captures a digit into Group 2 and then`\2{6}`

matches 6 values captured in Group 2 followed with end of string check with`$`

)`(?:\d{7,15})?`

- an optional group matching 7 to 15 digits (or an empty string, as it's optional)`$`

- end of string.