Jump to content

Trying to construct a regular expression that only accepts input with letters and numbers.


mstabosz
Go to solution Solved by requinix,

Recommended Posts

I thought this would be straightforward, but I'm missing something.  Here are the rules:

 

3 to 20 characters.

Letters either upper or lower case are allowed.

Numbers are allowed.

Nothing else is allowed.

 

So jsmith is okay, as is jsmith123, but jsmith! is FORBIDDEN.

 

So using what I know about regular expressions and a regular expressions tester at http://regexpal.com/, I came up with this:

 

[a-zA-Z0-9]{3,20}

 

That allows jsmith and jsmith123, which is good, but it also allows jsmith!, which is bad.  The regex tester highlights the allowed characters in all instances and leaves the exclamation point alone.  But what I want is an all or nothing thing.  If that ! gets in there, throw away the rest of the expression.  I have a feeling I'm misunderstanding something about regular expressions.

Link to comment
Share on other sites

Use the negative lookahead flag.

 

([a-zA-Z0-9+]{3,20}(?![^a-zA-Z0-9]))

 

Should do the trick.

 

Edit: I brushed up the regex a bit... and it didn't work out as I planned it to do.

I'll think of something else.

Edited by Irate
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.