Jump to content

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


terungwa
Go to solution Solved by 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.

Edited by terungwa
Link to comment
Share on other sites

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:)

Link to comment
Share on other sites

  • Solution

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:
Edited by terungwa
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.