user5558
user5558

Reputation: 25

regex expression in javascript

I am trying to build a regex in javascript to match a 9-digit number with these characteristics:

First 3 digits should not be ‘0’ ,

4th and 5th Digit should not be ‘0’,

Last 4 digits should not be ‘0000’,

First 3 digits should not be ‘666’,

Last 3 Digits Should not be greater than ‘899’

Can someone please help me out with this.

Here is my current regex:

/^666[^0]{3}[1-9]{2}0000$/

, but it’s not meeting the criteria

Upvotes: 1

Views: 70

Answers (3)

Akshey Bhat
Akshey Bhat

Reputation: 8545

Try This regular expression it will work ^(?!(000)|(666))[0-9]{3}[1-9]{2}[0-9][0-8][0-9]{2}(?<!0000)$. See demo here

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370789

Because all nine characters need to be a digit, you might use lookahead from the beginning to check that there are 9 digits followed by the end of the string, which will make the subsequent groups easier to manage. Then, you need to utilize character sets and negative lookahead. The first two conditions look to collapse together - the first five characters need to be other than 0:

/^(?=\d{9}$)(?!666)[^0]{5}(?!0000)\d[^9]/

const re = /^(?=\d{9}$)(?!666)[^0]{5}(?!0000).[^9]/;
`555555555
5555555555
055555555
555505555
666555555
555550000
555550001
555550900
555550953`
  .split('\n')
  .forEach(n => console.log(re.test(String(n))));

Explanation:

555555555   true
5555555555  false; 10 digits, not 9
055555555   false: has 0 in first 5 digits
555505555   false: has 0 in first 5 digits
666555555   false: starts with 666
555550000   false: ends with 0000
555550001   true
555550900   false: sixth digit is a 9 (so last 3 digits are 9xx, which is greater than 899)
555550953   false: same as above

https://regex101.com/r/Vpwbk0/1

Upvotes: 1

flyingfox
flyingfox

Reputation: 13506

Try this ^[^06]{3}[^0]{2}[^0][1-8][^0]{2}$

Below is my explanation for it

First 3 digits should not be ‘0’  
First 3 digits should not be ‘666’,->  ^[^06]{3} 
4th and 5th Digit should not be ‘0’, -> [^0]{2}
Last 4 digits should not be ‘0000’, -> [^0]{4}
Last 3 Digits Should not be greater than ‘899’ -> [1-8][^0]{2}$ 

Upvotes: 1

Related Questions