Created
March 21, 2015 15:17
-
-
Save susisu/f8d84dde53b8858ea706 to your computer and use it in GitHub Desktop.
楽しいメールアドレス
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
var lq = require("loquat"); | |
var atom = lq.alphaNum.or(lq.oneOf("!#$%&'*+-/=?^_`{|}~")); | |
var dotAtom = lq.char(".").then(atom).bind(function (c) { return lq.pure("." + c); }); | |
var normal = atom.bind(function (head) { | |
return dotAtom.or(atom).manyChar().bind(function (tail) { | |
return lq.pure(head + tail); | |
}); | |
}); | |
var quotedAtom = lq.alphaNum.or(lq.oneOf("!#$%&'*+-/=?^_`{|}~()<>[]:;@,. ")) | |
.or(lq.char("\\").then(lq.alphaNum.or(lq.oneOf("!#$%&'*+-/=?^_`{|}~()<>[]:;@,. \\\""))) | |
.bind(function (c) { return lq.pure("\\" + c); })); | |
var quoted = lq.char("\"").right(quotedAtom.manyChar()).left(lq.char("\"")) | |
.bind(function (q) { return lq.pure("\"" + q + "\""); }); | |
var local = quoted.or(normal); | |
var domainLetter = lq.alphaNum.or(lq.char("-")); | |
var domainPart = domainLetter.manyChar1(); | |
var domain = domainPart.bind(function (head) { | |
return lq.char(".").then(domainPart) | |
.bind(function (d) { return lq.pure("." + d); }) | |
.manyChar() | |
.bind(function (tail) { return lq.pure(head + tail); }); | |
}); | |
var hex = lq.digit.manyChar1().bind(function (s) { | |
var n = parseInt(s); | |
if (n > 255) { | |
return lq.unexpected(s); | |
} | |
else { | |
return lq.pure(s); | |
} | |
}); | |
var ip = lq.char("[").then(hex).bind(function (a) { | |
return lq.char(".").then(hex).bind(function (b) { | |
return lq.char(".").then(hex).bind(function (c) { | |
return lq.char(".").then(hex).bind(function (d) { | |
return lq.char("]").then(lq.pure("[" + [a, b, c, d].join(".") + "]")); | |
}); | |
}); | |
}); | |
}); | |
var domainName = domain.or(ip); | |
var addrSpec = local.bind(function (l) { | |
return lq.char("@").then(domainName).bind(function (d) { | |
return lq.pure(l + "@" + d); | |
}); | |
}); | |
var mailbox = lq.noneOf("<>").skipMany().then(lq.char("<").right(addrSpec).left(lq.char(">"))).try().or(addrSpec); | |
var examples = [ | |
"[email protected]", | |
"[email protected]", | |
"user+mailbox/[email protected]", | |
"!#$%&'*+-/=?^_`.{|}[email protected]", | |
"\"Abc@def\"@example.com", | |
"\"Fred\\ Bloggs\"@example.com", | |
"\"Joe.\\\\Blow\"@example.com", | |
"[email protected]", // error | |
"[email protected]", // error | |
"<[email protected]>", | |
"foo bar <[email protected]>" | |
]; | |
examples.forEach(function (example) { | |
var res = lq.parse(mailbox, "", example); | |
if (res.succeeded) { | |
console.log(res.value); | |
} | |
else { | |
console.log(res.error.toString()); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment