Skip to content

Instantly share code, notes, and snippets.

@mrsarm
Created January 27, 2025 21:32
Show Gist options
  • Save mrsarm/93a2d7448f46e5a3c34cecc716dda2f9 to your computer and use it in GitHub Desktop.
Save mrsarm/93a2d7448f46e5a3c34cecc716dda2f9 to your computer and use it in GitHub Desktop.
re-samples.js: JavaScript Regex examples
let personList = `First_Name: John, Last_Name: Doe
First_Name: Jane, Last_Name: Smith`;
// Adding a ? at the end of the named capturing group makes it optional, e.g. '... (?<lastname>\w+)?'
let regexpNames = /First_Name: (?<firstname>\w+), Last_Name: (?<lastname>\w+)/mg;
let match = regexpNames.exec(personList);
do {
console.log(`Hello ${match.groups.firstname} ${match.groups.lastname}`);
} while((match = regexpNames.exec(personList)) !== null);
const found = "team-1234-private".match(/^((?<context>team|user)-)?(?<ctxId>\d+)((?<isPrivate>)-private)?$/);
if (found) {
const { context, ctxId, isPrivate } = found.groups;
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment