| 1 | let sample = `a:b |
| 2 | \tc:d |
| 3 | \t:w |
| 4 | \t\te:n |
| 5 | :w |
| 6 | g:h`; |
| 7 | |
| 8 | |
| 9 | const parseBuilder = (str) => { |
| 10 | let lines = str.split("\n"); |
| 11 | const ref = {}; |
| 12 | for (let line of lines) { |
| 13 | const lineData = |
| 14 | /^(?<tabs>\s*)(?<name>\w*)(?<optional>\??):(?<regex>.*)/.exec( |
| 15 | line |
| 16 | ).groups; |
| 17 | const tabs = lineData.tabs.length; |
| 18 | if (!ref[tabs]) ref[tabs] = [lineData]; |
| 19 | else ref[tabs].push(lineData); |
| 20 | if (tabs) { |
| 21 | const parentRefInd = ref[tabs - 1].length - 1; |
| 22 | let parent = ref[tabs - 1][parentRefInd]; |
| 23 | if (!parent.children) parent.children = [lineData]; |
| 24 | else parent.children.push(lineData); |
| 25 | } |
| 26 | } |
| 27 | return ref[0]; |
| 28 | }; |
| 29 | |
| 30 | const buildToRegex = (build) => { |
| 31 | const re = buildToRegexRecursion(build, ""); |
| 32 | return re; |
| 33 | }; |
| 34 | |
| 35 | const buildToRegexRecursion = (build, re) => { |
| 36 | if (!build?.length) return re; |
| 37 | const val = build.shift(); |
| 38 | if (val.name) re += `(?P<${val.name}>${val.regex}`; |
| 39 | else re += `(?:${val.regex}`; |
| 40 | if (val.children) re += buildToRegexRecursion(val.children, ""); |
| 41 | re += `${val.optional})`; |
| 42 | |
| 43 | return buildToRegexRecursion(build, re); |
| 44 | }; |
| 45 | |
| 46 | const d = parseBuilder(sample); |
| 47 | |
| 48 | const b = buildToRegex(d); |
| 49 | console.log(b); |