Public
Edited
Sep 18, 2024
Paused
Importers
9 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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more