Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx: Must have at least one number and letter but no other characters / whitespace

Got a bit stuck (RegEx isn't my strong point at all!) - I need an expression that will validate against any string containing only numbers and letters but must have at least one of each (upper and lowercase are interchangeable and allowed). It cannot contain special characters or whitespace.

Doing some prior research I have found this but it doesn't exclude whitespace and despite my attempts to do so I cannot modify it to exclude whitespace and special characters:

^.*(?=.*\d)(?=.*[a-zA-Z]).*$

Some examples of strings that need to validate:

  • ieoEon43
  • 43ifsiojfdfs
  • 6i
  • ijf943kNFSfsf

Any help would be much appreciated! If it matters I am running these expressions in JavaScript.

like image 827
trvo Avatar asked Jul 07 '14 15:07

trvo


2 Answers

Try this:

/^(?=.*[a-z])(?=.*\d)[a-z\d]+$/i

Regex101 Demo

Explanation:

Regular expression visualization

Debuggex Demo

Edit: Fixed special characters issue.

like image 58
elixenide Avatar answered Oct 01 '22 07:10

elixenide


Another attempt for fun and glory! (it's shorter!)

^([a-z]+\d+|\d+[a-z]+)\w*$

Regular expression visualization

Debuggex Demo

EDIT3:

Made a small fix and it's now DOUBLE the speed of the other answer!!!

JSPERF

like image 35
Mosho Avatar answered Oct 01 '22 05:10

Mosho