假設我有三個字串模板:
A = `。
表 <name> {
<屬性名稱> <資料型別>
}
`
B = `
表 用戶 {
name varchar
}
`
C = `
表 價格 {
名稱
}
`
在這里,A是模板。而我希望B和C的格式與A相同。在這個例子中,C不匹配,所以它將拋出一個錯誤。而B則匹配。
而我希望占位符<name>或<data-type>能夠根據B映射到它們的值。這里,<name>應該是 "User",<attribute-name>應該是 "name",<data-type>應該是 "varchar"。
我可以做一個線性搜索并比較字串,但是有什么優雅的方法嗎?或者一個javascript庫?
uj5u.com熱心網友回復:
可能有一個更干凈的方法,但我想這里的一個重合詞可以幫助你。
這里有一個簡單的方法來匹配你的三個占位符。/^Table (w*) {
(w*) (w*)
}/gm
B = `。
表用戶 {
name varchar
}
`
C = ``表用戶 { name varchar } `
表 價格 {
名稱
}
`
function parseTemplate(str){
var regex = /^Table (w*) {
(w*) (w*)
}/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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
。function tpl2re(tpl) {
return new RegExp(tpl.replace(
/<(. ?)>/g,
($0, $1) => ' ( ? <' $1. replace(/W/g, '_') '>w ) '
))
}
A = ``
B = `
表 用戶 {
name varchar
}
`
C = `
表 價格 {
名稱
}
`
re = tpl2re(A)
m = B.match(re); console.log(m & & m.groups)
m = C.match(re); console.log(m & & m.groups)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324459.html
標籤:
