Skip to content

Instantly share code, notes, and snippets.

@spamwax
Last active April 27, 2023 06:53
Show Gist options
  • Save spamwax/c891473af3051191f9fe to your computer and use it in GitHub Desktop.
Save spamwax/c891473af3051191f9fe to your computer and use it in GitHub Desktop.
Solution to eloquentjavascript exercise second 2nd edition (Chapter 9) eloquent javascript
// Solution to eloquentjavascript exercise second 2nd edition
// Chapter 9
// http://eloquentjavascript.net/2nd_edition/preview/09_regexp.html
// regex Golf
verify(/ca[rt]/,
["my car", "bad cats"],
["camper", "high art"]);
verify(/pr?op/,
["pop culture", "mad props"],
["plop"]);
verify(/ferr(et|y|ari)/,
["ferret", "ferry", "ferrari"],
["ferrum", "transfer A"]);
verify(/ious\b/,
["how delicious", "spacious room"],
["ruinous", "consciousness"]);
verify(/\s[\.,;:]/,
["bad punctuation ."],
["escape the dot"]);
verify(/\w{7,}/,
["hottentottententen"],
["no", "hotten totten tenten"]);
verify(/\b[^e\s]+\b/,
["red platypus", "wobbling nest"],
["earth bed", "learning ape"]);
//----------------------------------------------------
// Quoting Style
var text = "'I'm the cook,' he said, 'it's my job.'";
var text = "'I'm the cook' he said, 'it's my job'";
console.log(text.replace(/(^)'|(\W)'|'(\W)|'($)/g, "$1$2\"$3"));
//----------------------------------------------------
// Numbers again
var number = /^(\+|-)?((\d+(\.\d*)?)|(\.\d+))(((e|E)(\+|-)?)\d+)?$/;
// or
// number = /^[+\-]?((\d+(\.\d*)?)|(\.\d+))(([eE][+\-]?)\d+)?$/;
// Tests:
["1", "-1", "+15", "1.55", ".5", "5.", "1.3e2", "1E-4",
"1e+12", "+1.e3", ".8e-3"].forEach(function(s) {
if (!number.test(s)) {
console.log("Failed to match '" + s + "'");
} else {
console.log(s, "matched correctly!");
}
});
["1a", "+-1", "1.2.3", "1+1", "1e4.5", ".5.", "1f5",
"."].forEach(function(s) {
if (number.test(s)) {
console.log("Incorrectly accepted '" + s + "'");
} else {
console.log(s, "not matched correctly!");
}
});
@owrrpon
Copy link

owrrpon commented Apr 27, 2023

For the quoting style, isn't this easier :
console.log(text.replace(/([^\w])'|^'/g, "$1""));

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