我有一个提供的符号数组,它可以是不同的。例如,像这样-['@']。每个符号必须出现一次。但是在字符串中,每个提供的符号只能有一个。
现在我这样做:
const regex = new RegExp(`^\w+[${validatedSymbols.join()}]\w+$`);
但是对于'='等符号,它也会返回错误。例如:
/^w+[@]w+$/.test('string@=string') // false
所以,我期望的结果是:
- 'string@string' - ok
- 'string@@string - not ok
使用复杂的正则表达式很可能不是最好的解决方案。我认为你最好创建一个验证函数。
在这个函数中,您可以在string
中找到所提供的symbols
的所有出现。然后返回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);
}
我想你在找以下内容:
const regex = new RegExp(`^\w+[${validatedSymbols.join()}]?\w+$`);
问号表示前一组的1或0。
您可能还需要转义validatedSymbols
中的符号,因为某些符号在regex
中具有不同的含义。编辑:
对于强制符号,更容易为每个符号添加一个组:
^w+(@w*){1}(#w*){1}w+$
其中组为:
(@w*){1}