djfkdjfkd39939
djfkdjfkd39939

Reputation: 393

Regex for Arrays within an Array

I have an array of arrays (call the outer array arr1) with numerous values which are all inner arrays. I am trying to validate that the inner arrays have the following format for its elements with arr1[1] provided as an example (the other elements of arr1, i.e. arr1[2], arr1[3], arr1[4], etc. are of the same format

arr1[1] = ['item1', 'item2', 'item3', 'item4', 'item5']:

item 1 - "abcdef" (variable number of letters)
item 2 - "abcdef" (variable number of letters)
item 3 - "abcdef" (variable number of letters) OR "abcdef asdf" (variable number of letters separated by one whitespace character)    
item 4 - "12345678" (eight digits)
item 5 - "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 so far (not sure how the second line works - got it from a different SO thread):

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.

Upvotes: 1

Views: 620

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

You can use the following:

item 1 - \w+ (variable number of letters)
item 2 - \w+ (variable number of letters)
item 3 - \w+(?:\s\w+)? (variable number of letters) OR 
                         (variable number of letters 
                          separated by one whitespace character)    
item 4 - \d{8} (eight digits)
item 5 - (?:\d{3}\s){2}\d{4} (telephone number with 3 digits 
                              followed by 3 digits followed by 4 
                              digits with two whitespace characters as shown)

EDIT: You can use ^\w+?,\s\w+?,\s\w+(?:\s\w+)?,\s\d{8},\s(?:\d{3}\s){2}\d{4}$ to directly validate the string.

Ex:

function validateStr(str) {
  return (/^\[\s'\w+?',\s'\w+?',\s'\w+(?:\s\w+)?',\s'\d{8}',\s'(?:\d{3}\s){2}\d{4}'\s\]$/).test(str);
}

Upvotes: 3

Pratik
Pratik

Reputation: 1138

You should have something like -

function checkTelephone(s) {
      return (/^(\d{3})\s(\d{3})\s(\d{4})$/).test(s);
}

This function returns false if the string does not match the telephone regular expression.

Upvotes: 0

Related Questions