-7

I want a simple validation <word must be Locate with length 6,SPACE,1 length integer,COMMA, 1 length integer,COMMA, 1 word must be either UP, DOWN, LEFT, RIGHT> and case of words don't matter. How would I do this? Preferably I'd like to do this using RegExp and I'll have an array of strings. i.e.) LOCaTe 9,0,uP

I have a simple array ["Locate", "9", "," ,"4", "up"] . This array will work. If I have an array like ["Locate"," asdf", "9", "," ,"4", "up"] that array wont work. It has to be a string then number then comma then number then string.

handlebears
  • 2,168
  • 8
  • 18

2 Answers2

2

I guess regex might not be necessary here, and you can likely script that with some methods similar to:

function check(arr = arr) {
 if (arr.length !== 5) {
  return false;
 }

 if (arr[0].toLowerCase() !== 'locate') {
  return false;
 }


 if (parseInt(arr[1]) === NaN || parseInt(arr[3]) === NaN) {
  return false;
 }

 if (arr[2] !== ',') {
  return false;
 }

 if (arr[4].toLowerCase() === 'up' || arr[4].toLowerCase() === 'left' || arr[4].toLowerCase() === 'right' || arr[4].toLowerCase() === 'down') {
  return true;
 } else {
  return false;
 }

 return true;
}

arr = ["Locate", "9", ",", "4", "UP"]
console.log(check(arr))

If you had to write an expression, then maybe an expression similar to:

^\[\s*"locate"\s*,\s*"\d"\s*,\s*"\s*,"\s*,\s*"\d"\s*,\s*"(?:up|down|right|left)"\s*\]$

might be OK to look into.

const regex = /^\[\s*"locate"\s*,\s*"\d"\s*,\s*"\s*,"\s*,\s*"\d"\s*,\s*"(?:up|down|right|left)"\s*\]$/gmi;
const str = `["Locate", "9", "," ,"4", "up"]
["LOCATE" , "8" , "," , "4", "down"]
["LoCATE" , "3" , "," , "0", "right"]
["LoCate" , "2" , "," , "5", "left"]
["LoCate" , "21" , "," , "5", "left"]`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
0

You can first convert the array into string (using join()), and then check the string with regExp.

function isValidArray(arr) {
  let str = arr.join(';');
  return (new RegExp(/(locate);\d;,;\d+;((up)|(down)|(left)|(right))/gi)).test(str)
}

const arr1 = ["Locate", "9", "," ,"4", "up"];
const arr2 = ["Locate"," asdf", "9", "," ,"4", "up"] ;

console.log(isValidArray(arr1)); // return true
console.log(isValidArray(arr2)); // return false
samhoooo
  • 176
  • 10