Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression for english & numeric characters only

What is the easiest way to check if an expression has English or number characters only? with no spaces and no other characters.

p.s - the first character cannot be a number. upper or lower case.

like image 624
geevee Avatar asked Mar 08 '11 11:03

geevee


2 Answers

I would use: /^[A-Za-z][A-Za-z0-9]*$/. Here are same examples:

/^[A-Za-z][A-Za-z0-9]*$/.test("expression");
/^[A-Za-z][A-Za-z0-9]*$/.test("EXPRESSION");
/^[A-Za-z][A-Za-z0-9]*$/.test("e123xpression");
/^[A-Za-z][A-Za-z0-9]*$/.test("E123xpression");
/^[A-Za-z][A-Za-z0-9]*$/.test("1expression");

Without boundaries (^ and $) regexp match any substring too.

EDIT: Updated invalid expression

like image 57
Grzegorz Gierlik Avatar answered Sep 18 '22 06:09

Grzegorz Gierlik


Easiest:

/^[a-z][a-z0-9]*$/i

explanation of the expression:

  • / - open expression
  • ^ - string must start here. Nothing before
  • [a-z] - find only one character between a to z, including
  • [a-z0-9]* - find any sequence of characters either between a to z including, or between 0-9 including (the "any sequence" part is the * in the end)
  • $ - string must end here. Nothing after
  • / - close expression
  • i - the expression is case insensitive

tested with the following cases

var tests = //key = case, value = expected results { "joe" : true //only lower case , "JOE" : true //only capital , "charsAndCaps" : true //mixed case , "ABC444" : true //caps and numbers , "AAaaAA3276" : true //mixed case with numbers , "111Joe" : false //starts with number , "112345" : false //only numbers , "asaaa$" : false //non-alphanumeric char in the end , "asaaaלא" : false //non-latin char in the end , "asaaнет" : false //non-latin char in the end , "#asaaa" : false //non-alphanumeric char in the start , "לאasaaa" : false //non-latin char in the start , "нетasaa" : false //non-latin char in the start , "aaלאasaa" : false //non-latin char in the middle , "sssнетaa" : false //non-latin char in the middle , "as&&aaa" : false //non-alphanumeric char in the middle , "" : false //empty string }

try it at: http://jsfiddle.net/erJ4H/161/

like image 32
Radagast the Brown Avatar answered Sep 20 '22 06:09

Radagast the Brown