我有一個提供的符號陣列,可以不同。例如,像這樣 - ['@']。每個符號出現一次是強制性的。但是在一個字串中,每個提供的符號只能有一個。現在我喜歡這樣:
const regex = new RegExp(`^\\w [${validatedSymbols.join()}]\\w $`);
但它也會在 '=' 等符號上回傳錯誤。例如:
/^\w [@]\w $/.test('string@=string') // false
所以,我期望的結果:
- '字串@字串' - 好的
- 'string@@string - 不行
現有的答案都沒有,對我沒有幫助:(
uj5u.com熱心網友回復:
使用復雜的正則運算式很可能不是最佳解決方案。我認為您最好創建一個驗證功能。
在此函式中,您可以找到所有出現symbols的string. false如果沒有找到匹配項,或者匹配項串列包含重復條目,則回傳。
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
const escapeRegExp = (string) => string.replace(/[.* ?^${}()|[\]\\]/g, '\\$&');
function validate(string, symbols) {
if (symbols.length == 0) {
throw new Error("at least one symbol must be provided in the symbols array");
}
const symbolRegex = new RegExp(symbols.map(escapeRegExp).join("|"), "g");
const symbolsInString = string.match(symbolRegex); // <- null if no match
// string must at least contain 1 occurrence of any symbol
if (!symbolsInString) return false;
// symbols may only occur once
const hasDuplicateSymbols = symbolsInString.length != new Set(symbolsInString).size;
return !hasDuplicateSymbols;
}
const validatedSymbols = ["@", "="];
const strings = [
"string!*string", // invalid (doesn't have "@" nor "=")
"string@!string", // valid
"string@=string", // valid
"string@@string", // invalid (max 1 occurance per symbol)
];
console.log("validatedSymbols", "=", JSON.stringify(validatedSymbols));
for (const string of strings) {
const isValid = validate(string, validatedSymbols);
console.log(JSON.stringify(string), "//=>", isValid);
}
uj5u.com熱心網友回復:
使用大括號 {1} 除了您只希望單次出現的字符。
uj5u.com熱心網友回復:
我認為您正在尋找以下內容:
const regex = new RegExp(`^\\w [${validatedSymbols.join()}]?\\w $`);
問號表示上一組的 1 或 0。
您可能還需要轉義符號,validatedSymbols因為某些符號在正則運算式中具有不同的含義
編輯:
對于強制符號,為每個符號添加一個組會更容易:
^\w (@\w*){1}(#\w*){1}\w $
該組在哪里:
(@\w*){1}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/467610.html
標籤:javascript 正则表达式
