Jump to content

Prevent a space (beginning, middle or end) charater in a string with regex


terungwa

Recommended Posts

I have a regex that validates a string.

I want to ensure there is no space in the string.

Thus far I have used the negative look ahead regex construct as shown below to match strings without spaces.

(?!.*(\s))

While this prevents space in between a word, all strings with space characters at the end or beginning are getting validated.

I do not want that at all.

 

This is the full regex script below:

$string = "#JebiamgoOeing0";
if (preg_match('/^.*(?=.{8,})(?!.*([A-Za-z0-9])\1{1})(?=.*[a-z])(?=.*[A-Z])(?!.*(\s))(?=.*[\d])(?=.*[\W]).*$/', $string))
{
    "do something";
}
else
{
   "do something else";
}

I need help in resolving this.

 

Thank you.

That looks like an expression to verify the complexity of a password. Why would you not want to allow spaces? Using a passphrase is much better than a password and should be encouraged.

Thank you Psycho for the input.

This is a learning exercise and I needed to be able to test my regex skills in implementing every permutation I could think of:)

I have fixed this, so no need to respond. It was a simple synthax error in my script!!

 

This is the code snippet that fixed this.


(?!.*(\s)) //Assert a string does not contain any white space characters after it using negative lookahead:
((?<!(\s)).*) //Assert a string does not contain any no white space characters before it using negative look behind:

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.