Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Created October 28, 2012 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhunzaker/3969319 to your computer and use it in GitHub Desktop.
Save nhunzaker/3969319 to your computer and use it in GitHub Desktop.
Fun with .match
var fs = require('fs');
var assert = require("assert");
// Example 1 ----------------------------------------- //
var myDomain = "www.nhunzaker.com/this_article";
assert( myDomain.match("nhunzaker.com") );
// Example 2 ----------------------------------------- //
var myString = "Hello, world! My name is Nate Hunzaker!";
var name = myString.match(/My name is (.*) (.*)!/);
assert.equal(name[1], "Nate");
assert.equal(name[2], "Hunzaker");
// Example 3 ----------------------------------------- //
var story = fs.readFileSync("wotw.txt").toString();
var pattern = "(.*)\\:(.*)\n";
var lines = story.match(new RegExp(pattern, "g") );
var data = {};
lines.forEach(function(line) {
var match = line.match( new RegExp(pattern) );
if (match) {
var key = match[1].toLowerCase();
var value = match[2].trim();
data[key] = value;
}
});
assert.equal(data.title, "The War of the Worlds");
assert.equal(data.author, "H.G. Wells");
assert.equal(data.body.substring(0, 12), "No one would");
console.log("Good to go!");
TITLE: The War of the Worlds
AUTHOR: H.G. Wells
BODY: No one would have believed in the last years of the nineteenth century that this world was being watched keenly and closely by intelligences...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment