Public
Edited
Sep 18, 2024
Paused
Importers
10 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// The individual strings.
strings = input.split(/\n/)
Insert cell
// Create the pattern.
pattern = new RegExp(createPattern(strings, { anchor, escape: !escapeChars ? d => d : undefined }))
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function createPattern(strings, {escape = escapeRegExp, anchor = true} = {}) {
const pattern = collapse(expand(strings), {escape});
return anchor ? `^(${pattern})$` : pattern;
}
Insert cell
// Create a Patricia-Trie from an array of strings.
function expand(strings, {merge = true} = {}) {
const str = strings.slice().sort();
// prefix, offset, start index, end index
const walk = (p = "", o, i0, i1) => {
const children = [];
for(let i = i0, c; i < i1; i++) {
c = str[i]?.[o];
if(i + 1 < i1 && c === str[i + 1]?.[o]) continue;
if(i + 1 === i1 && c === undefined) continue;
children.push(walk(c, o + 1, i0, i + 1));
i0 = i + 1;
}
if(children.length === 1 && merge) return [p + children[0][0], children[0][1]];
return [p, children];
};
return walk("", 0, 0, str.length);
}
Insert cell
// Flatten a Patricia-Trie into a regular expression.
function collapse(tree, {escape = escapeRegExp} = {}) {
const toString = ([p, children]) => {
p = escape(p);
if(!children.length) return p;
return `${p}(${children.map(toString).join("|")})`;
};
return toString(tree);
}
Insert cell
// https://github.com/tc39/proposal-regex-escaping/blob/main/polyfill.js
escapeRegExp = s => String(s).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more