Javascript正则表达式仅适用于英文和数字字符

gee*_*vee 2 javascript regex

检查表达式是仅包含英文字符还是数字字符的最简单方法是什么?没有空格,没有其他字符.

ps - 第一个字符不能是数字.大写或小写.

Grz*_*lik 8

我会用:/^[A-Za-z][A-Za-z0-9]*$/.以下是相同的例子:

/^[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");
Run Code Online (Sandbox Code Playgroud)

没有边界(^和$)regexp也匹配任何子字符串.

编辑:更新了无效表达式


Rad*_*own 7

最简单的:

/^[a-z][a-z0-9]*$/i
Run Code Online (Sandbox Code Playgroud)

表达式说明:

  • / -开放式表达
  • ^-字符串必须从此处开始。没事
  • [a-z] -在a到z之间仅找到一个字符,包括
  • [a-z0-9]* -查找包含a到z或包含0-9的任何字符序列(“任何序列”部分的末尾是*)
  • $-字符串必须在此处结束。没事
  • / -密切表达
  • i -表达式不区分大小写

经过以下情况测试

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 }

请尝试:http : //jsfiddle.net/erJ4H/161/