Skip to content

Instantly share code, notes, and snippets.

@westc
Last active January 12, 2024 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/f5a93d741bddc38299f1da8cf806fd22 to your computer and use it in GitHub Desktop.
Save westc/f5a93d741bddc38299f1da8cf806fd22 to your computer and use it in GitHub Desktop.
Extracts substrings from the given `string` by using `regexp`.
/**
* Extracts substrings from the given `string` by using `regexp`.
* @type {{
* (regexp: RegExp, string: string) => RegExpExecArray;
* <T>(regexp: RegExp, string: string, handler: (matches: RegExpExecArray) => T) => T;
* }}
*/
const extract = (regexp, string, handler) => {
const matches = regexp.exec(string) ?? [];
return handler ? handler(matches) : matches;
};
/**
* Extracts substrings from the given `string` by using `regexp`.
* @type {{
* (regexp: RegExp, string: string) => Record<string,string>;
* <T>(regexp: RegExp, string: string, handler: (matches: RegExpExecArray) => T) => T;
* }}
*/
const extractGroups = (regexp, string, handler) => {
const matches = regexp.exec(string) ?? [];
return !handler ? matches.groups ?? {} : handler(matches);
};
const sentences = [
'Hi!',
'Hello world!',
'Hello crazy world.'
];
for (const sentence of sentences) {
// Extracts the first and second word from the given string.
const [first, second] = extract(
/(\S+)\s+(\S+)/,
sentence,
([match, first, second]) => [first, second]
);
console.log({first, second});
}
// Prints {first: undefined, second: undefined}
// Prints {first: "Hello", second: "world!"}
// Prints {first: "Hello", second: "crazy"}
const sentences = [
'Hi!',
'Hello world!',
'Hello crazy world.'
];
for (const sentence of sentences) {
// Extracts the first and second word from the given string.
const {first, second} = extractGroups(
/(?<first>\S+)\s+(?<second>\S+)/,
sentence
);
console.log({first, second});
}
// Prints {first: undefined, second: undefined}
// Prints {first: "Hello", second: "world!"}
// Prints {first: "Hello", second: "crazy"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment