Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!