UNPKG

diffusion

Version:

Diffusion JavaScript client

33 lines (30 loc) 1.13 kB
/** * Create a regex matcher function for a given regex expression, with an * optional context for RegEx construction error messages. * <P> * The returned function will evaluate the generated regex across the entire * region of the given input. This is equivalent to Matcher.matches in Java. * * @param {String} s - The regular expression * @param {String} [context=""] - The optional context message * @returns {Function} The tester function * @throws Error if the regex couldn't be created */ function regex(s, context) { context = context || ""; if (s === "") { throw new Error("Empty regular expression [" + context + "]"); } try { var r = new RegExp(s); return function(test) { // Because JS regex will match any part of the test string, // we have to verify the results to ensure the entire part matches var m = r.exec(test); return m && m[0] === test; }; } catch (e) { throw new Error("Bad regular expression [" + e.message + ", " + context + "]"); } } module.exports = regex;