@syntropiq/py-regex
Version:
Python-compatible regular expressions for TypeScript/JavaScript, mirroring Python's re/regex API.
66 lines • 1.94 kB
JavaScript
// Pythonic regex API wrapper for py-regex
import { compileRegex } from './compile.js';
import { escapeRegex } from './escape.js';
function makeMatch(pcreMatch, namedGroups) {
// Map group names to values
const groups = {};
for (const [name, idx] of Object.entries(namedGroups)) {
if (pcreMatch[idx])
groups[name] = pcreMatch[idx].value;
}
// group(0) is the full match
return {
group(nameOrIndex) {
if (typeof nameOrIndex === 'number') {
return pcreMatch[nameOrIndex]?.value;
}
else if (nameOrIndex in groups) {
return groups[nameOrIndex];
}
return undefined;
},
groups,
fullMatch: pcreMatch[0]?.value ?? '',
};
}
async function compile(pattern, flags) {
// TODO: support flags
const regex = await compileRegex(pattern);
const namedGroups = regex.getNamedGroups();
return {
fullmatch(text) {
const m = regex.exec(text);
if (!m)
return null;
// Only match if the full string matches
if (m[0].index === 0 && m[0].length === text.length) {
return makeMatch(m, namedGroups);
}
return null;
},
match(text) {
const m = regex.exec(text);
if (!m)
return null;
// Match must start at index 0
if (m[0].index === 0) {
return makeMatch(m, namedGroups);
}
return null;
},
search(text) {
const m = regex.exec(text);
if (!m)
return null;
return makeMatch(m, namedGroups);
},
test(text) {
return regex.test(text, 0);
},
};
}
export const regex = {
compile,
escape: escapeRegex,
};
//# sourceMappingURL=regex.js.map