Home > Net >  how to negate spaces in regex [duplicate]
how to negate spaces in regex [duplicate]

Time:09-30

i'm trying to not allow leading or trailing spaces for this password validation:

const passRegExp= /^.*(?=.{8,})((?=.*[!@#$%^&*()\-_= {};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1}).*$/;

i've tried to add /S like so:

const passRegExp= /^/S.*(?=.{8,})((?=.*[!@#$%^&*()\-_= {};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1})./S*$/;

and like so:

const passRegExp= /^./S*(?=.{8,})((?=.*[!@#$%^&*()\-_= {};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1}).*/S$/;

but it doesn't seem to work

CodePudding user response:

The most consistent and read-friendly way is to add one more lookahead matching group checking start and finish symbols to be non-space:

^[^\s].*[^\s]$

The result regexp will be:

^.*(?=^[^\s].*[^\s]$)(?=.{8,})((?=.*[!@#$%^&*()\-_= {};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1}).*$
  • Related