Examples
Render to SVG
Get a self-contained SVG string in one call — drop it into the page or save it to a file.
import { regexToSvg } from '@wzo/regex-diagram'
// Returns a self-contained SVG string, or null if the regex is invalid/broken.
const svg = regexToSvg('(?<year>\\d{4})-(?<month>\\d{2})', 'g')
document.querySelector('#out')!.innerHTML = svg ?? 'invalid regex'
Validate a regex
parseRegex returns syntax errors and semantic issues alike (e.g. an assertion
that never matches).
import { parseRegex } from '@wzo/regex-diagram'
const result = parseRegex('a$\\d') // valid syntax, but never matches
if (!result.ok || result.issues.length) {
for (const issue of result.issues) {
console.warn(issue.message, 'at', issue.start)
}
}
Explain a regex
Get a token-by-token explanation and print it indented by depth.
import { explainRegex } from '@wzo/regex-diagram'
for (const step of explainRegex('(?<y>\\d{4})') ?? []) {
console.log(' '.repeat(step.depth) + step.token + ' — ' + step.text)
}
Lower-level control
Two steps: lay out the AST into a model, then render it to SVG yourself.
import { buildDiagram, parseRegex, renderToSvg } from '@wzo/regex-diagram'
const parsed = parseRegex('a|b|c')
if (parsed.ok) {
const diagram = buildDiagram(parsed.ast) // positioned model
const svg = renderToSvg(diagram, 'i') // model → SVG string
}