简体   繁体   English

用于验证特殊字符串的Javascript正则表达式

[英]Javascript regular expression for validating a special string

I am new to javascript regular expressions.Any-way i want to valiadate a string that matches some conditions 我是javascript正则表达式的新手,无论如何,我想对符合某些条件的字符串进行变体化

Here are the conditions 这是条件

1.String contains only 9 characters 1.字符串仅包含9个字符

2.First two letters must be alphabets. 2.前两个字母必须是字母。

3.third letter must be '-' this. 3.第三个字母必须为“-”。

4.Remaining 6 letters must be digits 4.剩余的6个字母必须是数字

function validateInput(str){
   if(str.length>9){
    alert("Exeeds maximum limit");
  }
}

How can i do the rest of the validations using regex? 我如何使用正则表达式进行其余的验证?

The following regex matches exactly what you described: 以下正则表达式与您所描述的完全匹配:

 /^[a-z]{2}-\d{6}$/i

regex101 demo regex101演示

  • ^ matches the start of string (preventing matches in the middle of the string) ^匹配字符串的开头(防止在字符串中间匹配)
  • [az]{2} matches 1 letter, repeated 2 times (thus it matches 2 letters). [az]{2}匹配1个字母,重复2次(因此匹配2个字母)。
  • - matches a literal dash -匹配文字破折号
  • \\d{6} matches a digit, repeated 6 times (6 digits). \\d{6}与一个数字匹配,重复6次(6个数字)。
  • $ matches the end of string. $匹配字符串的结尾。
  • Mode : /i - case-insensitive match. 模式/i不区分大小写的匹配。 So [az] also matches uppercase letters as well. 因此[az]也匹配大写字母。

Code

 function validateInput(str){ if(/^[az]{2}-\\d{6}$/i.test(str)){ document.body.innerText += str + "\\t- Valid input\\n"; } else { document.body.innerText += str + "\\t- Invalid input\\n"; } } validateInput("xY-123456"); validateInput("abc-12345"); 

Note: using document.body.innerText as a way to output in the Code Snippet, but it shouldn't be used in your code 注意:使用document.body.innerText作为代码片段中的输出方式,但是不应在代码中使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM