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?
CodePudding user response:
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));
CodePudding user response:
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)