Created
March 19, 2018 18:26
-
-
Save jonurry/148f64af152854b591e8a512a9a95d34 to your computer and use it in GitHub Desktop.
9.1 RegExp Golf (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Refer to the table in the chapter summary for help. Test each solution with a few test strings.