Home > Blockchain >  Regex to not match a pattern in Javascript
Regex to not match a pattern in Javascript

Time:08-08

I need a reqular expression to not match this (/^[a-zA-Z][a-zA-Z0-9] $/) pattern, where the string needs to start with alphabet followed by number and alphabet, with no special characters.

I tried with (/^?![a-zA-Z]?![a-zA-Z0-9] $/) and not able to get appropriate answer.

Example:

P123454(Invalid)
PP1234(Invalid)
1245P(valid)
@#$124(valid) 

Thanks in advance.

CodePudding user response:

^ means start with, So it should start with an alphabetic letter, then any number \d of alphabetic letters a-z with i case insensitive flag.

const check = (str) => {
   return /^[^a-z].*/i.test(str)
}


console.log(check('P123454'))
console.log(check('PP1234'))
console.log(check('1245P'))
console.log(check('@#$124'))

CodePudding user response:

This regex might be helpful:

/^[^a-zA-Z] .*$/g

Your every valid input (from the question) should be a match.

Regex 101 Demo

Explanation:

  • Does not allow string starting with a-zA-Z
  • Everything after than is allowed (I'm not sure if this is a requirement)
  • Related