我正在撰寫一個矩陣計算器,用戶在其中輸入多個矩陣,然后撰寫一個包含所需矩陣的方程。為了驗證等式,我想要一個正則運算式,如果字符不是來自組[az , 0-9 , . , , - , * , ^ , ( , ) ]被找到。我創建了一個字串陣列來測驗這個正則運算式,它除了最后一個字串外都可以作業。奇怪的是,我已經在 regex101 上對此進行了測驗,并且在該網站上,正則運算式按計劃作業。如何修改我的正則運算式以使最后一個字串回傳“true”以及回傳“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
);
})
uj5u.com熱心網友回復:
在"A\B"被剝奪了它逃跑的時候JS插值的字串。
由于沒有轉義 B 特殊字符,轉義
在初始語言決議中被剝離。
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
);
})
uj5u.com熱心網友回復:
這不是正則運算式問題,它是您在最后一個條目中定義字串的方式,即“A\B”,您需要使用另一個斜線轉義斜線,即“A\\B”,否則將被忽略。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354531.html
標籤:javascript 正则表达式
