简体   繁体   English

各种正则表达式验证

[英]Various Regex Validation

I'm new to regex. 我是正则表达式的新手。 I have an array (call it arr1) with assorted values. 我有一个带有各种值的数组(称为arr1)。 I am trying to validate that it has the following format for its elements with arr1[x] provided as an example 我试图以提供的示例arr1 [x]来验证其元素具有以下格式

arr1[x] = "item1, item2, item3, item4, item5":

item 1 - "abcdef" (variable number of letters) or "abcdef asdf" (variable number of letters separated by one whitespace character)
item 2 - "abcdef" (variable number of letters) or "abcdef asdf" (variable number of letters separated by one whitespace character)
item 3 - "12345678" (eight digits)
item 4 - "123 456 7890" (telephone number with 3 digits followed by 3 digits followed by 4 digits with two whitespace characters as shown)

Here is a snippet of what I have for phone number validation (not sure how the second line works - got it from a different SO thread): 这是我用于电话号码验证的代码片段(不确定第二行的工作方式-是从其他SO线程获得的):

function f(s) {
  var s2 = (""+s).replace(/\D/g, '');
  var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
}

Thanks in advance for any assistance. 在此先感谢您的协助。

You can try this regex to account for all your cases: 您可以尝试使用此正则表达式解决所有情况:

^(?:[a-z]+(?: [a-z]+)?|\d{8}|\d{3} \d{3} \d{4})$

Use it with i option, eg: i选项一起使用,例如:

var re = /^(?:[a-z]+(?: [a-z]+)?|\d{8}|\d{3} \d{3} \d{4})$/i; 
if (re.exec(s) !== null) {
    return true;
}

Have a look at the demo . 看一下演示

 var re = /^(?:[az]+(?: [az]+)?|\\d{8}|\\d{3} \\d{3} \\d{4})$/i; var str = 'abcdef'; if (re.exec(str) !== null) { alert(true); } 

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

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