Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 19, 2018 18:26
Show Gist options
  • Save jonurry/148f64af152854b591e8a512a9a95d34 to your computer and use it in GitHub Desktop.
Save jonurry/148f64af152854b591e8a512a9a95d34 to your computer and use it in GitHub Desktop.
9.1 RegExp Golf (Eloquent JavaScript Solutions)
// the letters 'ca' followed by one of 'r' or 't'
verify(/ca[rt]/,
["my car", "bad cats"],
["camper", "high art"]);
// 'p' optionally followed by 'r' followed by 'op'
verify(/pr?op/,
["pop culture", "mad props"],
["plop"]);
// 'ferr' followed by 'et' or 'y' or 'ari'
verify(/ferr(et|y|ari)/,
["ferret", "ferry", "ferrari"],
["ferrum", "transfer A"]);
// 'ious' followed by a word boundary
verify(/ious\b/,
["how delicious", "spacious room"],
["ruinous", "consciousness"]);
// a whitespace character followed by one of '.' or ',' or ':'or ';'
verify(/\s[.,:;]/,
["bad punctuation ."],
["escape the period"]);
// 7 or more word characters grouped together
verify(/\w{7,}/,
["hottentottententen"],
["no", "hotten totten tenten"]);
// one or more words not containing an e
verify(/\b[^\We]+\b/,
["red platypus", "wobbling nest"],
["earth bed", "learning ape"]);
function verify(regexp, yes, no) {
// Ignore unfinished exercises
if (regexp.source == "...") return;
for (let str of yes) if (!regexp.test(str)) {
console.log(`Failure to match '${str}'`);
}
for (let str of no) if (regexp.test(str)) {
console.log(`Unexpected match for '${str}'`);
}
}
let re = /\b[^\We]+\b/;
console.log("red platypus".match(re));
console.log("wobbling nest".match(re));
console.log("earth bed".match(re));
console.log("learning ape".match(re));
@jonurry
Copy link
Author

jonurry commented Mar 19, 2018

Regular Expressions

9.1 RegExp Golf

Code golf is a term used for the game of trying to express a particular program in as few characters as possible. Similarly, regexp golf is the practice of writing as tiny a regular expression as possible to match a given pattern and only that pattern.

For each of the following items, write a regular expression to test whether any of the given substrings occur in a string. The regular expression should match only strings containing one of the substrings described. Do not worry about word boundaries unless explicitly mentioned. When your expression works, see whether you can make it any smaller.

  • car and cat
  • pop and prop
  • ferret, ferry, and ferrari
  • Any word ending in ious
  • A whitespace character followed by a period, comma, colon, or semicolon
  • A word longer than six letters
  • A word without the letter e

Refer to the table in the chapter summary for help. Test each solution with a few test strings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment