簡體   English   中英

僅適用於英文和數字字符的Javascript正則表達式

[英]Javascript regular expression for english & numeric characters only

檢查表達式是否僅包含英文或數字字符的最簡單方法是什么? 沒有空格和其他字符。

ps-第一個字符不能為數字。 大寫或小寫。

我會使用: /^[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");

沒有邊界( ^$ )的regexp也匹配任何子字符串。

編輯:更新無效的表達式

最簡單的:

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

表達式說明:

  • / -打開表達式
  • ^ -字符串必須從此處開始。 沒事
  • [az] -僅找到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/

試試這個:

/^[a-z][a-z\d]*$/i

添加一些示例:

/^[a-z][a-z\d]*$/i.test("check#$#"); // false
/^[a-z][a-z\d]*$/i.test("1check"); // false
/^[a-z][a-z\d]*$/i.test("check1"); // true 
/^[a-z][a-z\d]*$/i.test("cHEck1"); // true

使用這個: [a-zA-Z][a-zA-Z0-9]*

/ ^ [A-Za-z \\ d] + $

/^[A-Za-z\d]+$.test("TEST1"); // true
/^[A-Za-z\d]+$.test("Test2"); // true
/^[A-Za-z\d]+$.test("test3"); // true 
/^[A-Za-z\d]+$.test("4TEST"); // true
/^[A-Za-z\d]+$.test("5Test"); // true
/^[A-Za-z\d]+$.test("6test"); // true 
/^[A-Za-z\d]+$.test("TE7ST"); // true
/^[A-Za-z\d]+$.test("Te8st"); // true
/^[A-Za-z\d]+$.test("te9st"); // true 

試試這個/^[az]+[a-z0-9]*$/i

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM