Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active February 24, 2021 08:57
Embed
What would you like to do?
concatRegexes
const createConcatenator = escape => (...regexes) => {
const join = regexes
.map(x => (x instanceof RegExp ? regexToString(x) : escape(x)))
.join("");
const flags = regexes
.map(x => x instanceof RegExp && x.flags)
.filter(Boolean)
.join("");
const uniq = [...new Set(flags)].join("");
return new RegExp(join, uniq);
};
export const concatRegexes = createConcatenator(escapeRegExp);
export const concatRegexesUnescaped = createConcatenator(String);
function regexToString(value) {
return value.toString().replace(/^\/|\/[gi]*$/g, "");
}
// unused but can be useful
function stringToRegex(value, flags) {
return new RegExp(escapeRegExp(value));
}
function escapeRegExp(value) {
// $& means the whole matched string
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\n/g, "\\n");
}
const createConcatenator = (escape: (x: string) => string) => (
...regexes: (RegExp | string)[]
) => {
const join = regexes
.map(x => (x instanceof RegExp ? regexToString(x) : escape(x)))
.join('');
const flags = regexes
.map(x => x instanceof RegExp && x.flags)
.filter(Boolean)
.join('');
const uniq = [...new Set(flags)].join('');
return new RegExp(join, uniq);
};
export const concatRegexes = createConcatenator(escapeRegExp);
export const concatRegexesUnescaped = createConcatenator(String);
function regexToString(value: RegExp) {
return value.toString().replace(/^\/|\/[gi]*$/g, '');
}
// unused but can be useful
function stringToRegex(value: string, flags: string) {
return new RegExp(escapeRegExp(value));
}
function escapeRegExp(value: string) {
// $& means the whole matched string
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\n/g, '\\n');
}
import { concatRegexes } from './concatRegexes.ts'
const integer = /(\d+(?:,\d{3})*)/;
const myRegex = concatRegexes(
/^Tu saldo es de €/,
integer,
'. Puedes retirar €', // dot is escaped
integer,
/ hoy mismo (?<name>\w+)!$/
);
const match = 'Tu saldo es de €10. Puedes retirar €2 hoy mismo Matias!'.match(myRegex)
const saldo = match[1];
const puedoRetirar = match[2];
const nombre = match.groups.name;
console.log({ myRegex, saldo, puedoRetirar, nombre })
/*
Output:
{
myRegex: /^Tu saldo es de €(\d+(?:,\d{3})*)\. Puedes retirar €(\d+(?:,\d{3})*) hoy mismo (?<name>\w+)!$/
nombre: "Matias"
puedoRetirar: "2"
saldo: "10"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment