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

108
Visualizações
Compare 2 string templates

Let's say I have 3 string templates:

A = `
Table <name> {
<attribute-name> <data-type>
}
`
B = `
Table User {
name varchar
}
`
C = `
Table Price {
name
}
`

Here, A is the template. And I want B and C to be in the same format as A. In the example, C does not match, so it will throw an error. Whereas B matches.

And I want the placeholders <name> or <data-type> to map onto their values according to B. Here, <name> should be "User" and <attribute-name> should be "name" and <data-type> should be "varchar".

I can do a linear search and compare the strings, but is there any elegant approach to this? or a javascript library?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There's probably an even cleaner approach, but I think a regex here can assist you.

Here's a simple one to match your three placeholders: /^Table (\w*) {\n(\w*) (\w*)\n}/gm

B = `
Table User {
name varchar
}
`
C = `
Table Price {
name
}
`

function parseTemplate(str) {
  var regex = /^Table (\w*) {\n(\w*) (\w*)\n}/gm
  var matches = regex.exec(str);
  if (matches && matches.length == 4) {
    return {
      name: matches[1],
      'attribute-name': matches[2],
      'data-type': matches[3]
    };
  } else return null;
}

console.log(parseTemplate(B));
console.log(parseTemplate(C));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can convert the template to a regular expression by replacing <...> placeholders with named groups and then match your outputs against it (assuming each a placeholder is equivalent to \w+):

function tpl2re(tpl) {
    return new RegExp(tpl.replace(
        /<(.+?)>/g,
        ($0, $1) => '(?<' + $1.replace(/\W/g, '_') + '>\\w+)'
    ))
}

A = `
Table <name> {
<attribute-name> <data-type>
}
`

B = `
Table User {
name varchar
}
`
C = `
Table Price {
name
}
`

re = tpl2re(A)
m = B.match(re); console.log(m && m.groups)
m = C.match(re); console.log(m && m.groups)

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