3 var extend = require('extend-shallow');
4 var safe = require('safe-regex');
7 * The main export is a function that takes a `pattern` string and an `options` object.
10 & var not = require('regex-not');
11 & console.log(not('foo'));
12 & //=> /^(?:(?!^(?:foo)$).)*$/
15 * @param {String} `pattern`
16 * @param {Object} `options`
17 * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`.
21 function toRegex(pattern, options) {
22 return new RegExp(toRegex.create(pattern, options));
26 * Create a regex-compatible string from the given `pattern` and `options`.
29 & var not = require('regex-not');
30 & console.log(not.create('foo'));
31 & //=> '^(?:(?!^(?:foo)$).)*$'
33 * @param {String} `pattern`
34 * @param {Object} `options`
39 toRegex.create = function(pattern, options) {
40 if (typeof pattern !== 'string') {
41 throw new TypeError('expected a string');
44 var opts = extend({}, options);
45 if (opts.contains === true) {
46 opts.strictNegate = false;
49 var open = opts.strictOpen !== false ? '^' : '';
50 var close = opts.strictClose !== false ? '$' : '';
51 var endChar = opts.endChar ? opts.endChar : '+';
54 if (opts.strictNegate === false) {
55 str = '(?:(?!(?:' + pattern + ')).)' + endChar;
57 str = '(?:(?!^(?:' + pattern + ')$).)' + endChar;
60 var res = open + str + close;
61 if (opts.safe === true && safe(res) === false) {
62 throw new Error('potentially unsafe regular expression: ' + res);
72 module.exports = toRegex;