Jump to content

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


mstabosz

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.

It's less "all or nothing" but instead "everything in the string from the beginning to the end".

^[a-zA-Z0-9]{3,20}$
^ and $ meaning beginning- and end-of string respectively.

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.

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.