I am writing a matrix calculator, in which the user enters a number of matrices and then writes an equation including the desired matrix. To verify the equation, I want a regex that returns 'true' if a character is not from the group [a-z , 0-9 , . , , - , * , ^ , ( , ) ] is found. I've created an array of strings to test this regex, and it works with the exception of the final string. The strange this is that I've tested this on regex101, and on that website, the regex works as planned. How can I modify my regex in order for the last string to return 'true' as well as the other strings that returned 'true'?
let invalidCharRGX = /[^a-z0-9\.\ \-\*\^\(\)]/gi;
let strArr = [
"A B-C", //1 should return false
"(A B)-C", //2 should return false
"A^ B^-C", //3 should return false
"A*B-C", //4 should return false
"2.5A C", // 5 should return false
"A=B", //6 should return true
"[A-B]", //7 should return true
"A&B", //8 should return true
"A\B" //9 should return true
];
strArr.forEach((word, index) => {
console.log(invalidCharRGX.test(word),
word.match(invalidCharRGX),
index 1
);
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
The "A\B"
is stripped of it escape when JS interpolates the string.
Since there is no escape-B special character, the escape is stripped off
in the initial language parsing.
let invalidCharRGX = /[^a-z0-9\.\ \-\*\^\(\)]/gi;
let strArr = [
"A B-C", //1 should return false
"(A B)-C", //2 should return false
"A^ B^-C", //3 should return false
"A*B-C", //4 should return false
"2.5A C", // 5 should return false
"A=B", //6 should return true
"[A-B]", //7 should return true
"A&B", //8 should return true
"A\\B", //9 should return false
"A\B" //10 should return true
];
strArr.forEach((word, index) => {
console.log(word,
invalidCharRGX.test(word),
word.match(invalidCharRGX),
index 1
);
})
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
This isnt regex problem, its the way you have defined the string in your last entry i.e "A\B", you need to escape slash with another one i.e "A\\B", otherwise its ignored.