Regex tricks

Programmers hate #2

Quickies

Matching exceptions to discard them

When trying to match some string except in some situations:

NotThis|NorThis|(ButThis)

Often simpler than trying to exclude via lookbehind, conditionals, parity checks, etc. Even \K — when using a compatible flavor, drops previous character from the match — becomes unwieldy when the exceptions are a bit complex.

It works by matching all the exceptions, and then only looking at the first matching group.

Downsides:

Example usage in JavaScript:

const regex = /NotThis|NorThis|(ButThis)/g;
const matches = [];
let m;
while (m = regex.exec(str)) {
	if (typeof m[1] === "string") {
		matches.push(m[1]);
	}
}

Or with a generator function:

function* extract(str) {
	const regex = /NotThis|NorThis|(ButThis)/g;
	let m;
	while (m = regex.exec(str)) {
		if (typeof m[1] === "string") {
			yield m[1];
		}
	}	
}

For the full explanation and a good roundup of alternatives, see this article.