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

270
Visualizações
Possible to get 'regex source' from match?

I can get the source of a regex when it's defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*

Or:

let r2 = /el*/;
console.log(r2.source);
// el*

Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:

let m = "Hello".match(/el*/);
console.log(m.source?);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No,

quoting the documents of the match() function

Return value

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

So the return value is an array (you can test it by Array.isArray(m)// true)

However, the returned array has some extra information about the ocurred match (like groups, index and original input) but none of them include the original regex used to get the match

So there is no way to get that information from the match because its not returned by the matching function

about 4 years ago · Juan Pablo Isaza Relatório

0

The match result by itself cannot lead to the original regex, simply because different regexes can lead to the same result, even on the same string. Take for example the string "abcd" - all the following regexes: /abcd/, /a..d/ /a.*/ and many more, would match the string exactly the same way.

The only way you could retrive the original regex is if a reference to the regex was literally stored by the match() method inside the returned object. There is no reason to think that's the case, but you can implement your own match function that would do. Something like

function myMatch(str, regex) {
  var match = str.match(regex);
  if (match === null) {
    match = [null];
  }
  match.source = regex;
  return match;
}
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