Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda