Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
How can i check for only one occurence only of each provided symbol?

I have a provided array of symbols, which can be different. For instance, like this - ['@']. One occurrence of each symbol is a mandatory. But in a string there can be only one of each provided sign.

Now I do like this:

const regex = new RegExp(`^\\w+[${validatedSymbols.join()}]\\w+$`);

But it also returns an error on signs like '=' and so on. For example:

/^\w+[@]\w+$/.test('string@=string')  // false

So, the result I expect:

  • 'string@string' - ok
  • 'string@@string - not ok
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Using a complex regex is most likely not the best solution. I think you would be better of creating a validation function.

In this function you can find all occurrence of the provided symbols in string. Then return false if no occurrences are found, or if the list of occurrences contains duplicate entries.

// 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);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

I think you are looking for the following:

const regex = new RegExp(`^\\w+[${validatedSymbols.join()}]?\\w+$`);

The question mark means 1 or 0 of the previous group.

You might also need to escape the symbols in validatedSymbols as some symbols have a different meaning in regex

Edit:

For mandatory symbols it would be easier to add a group per symbol:

^\w+(@\w*){1}(#\w*){1}\w+$

Where the group is:

(@\w*){1}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda