alm
Version:
The best IDE for TypeScript
74 lines (73 loc) • 2.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function createRegExp(searchString, isRegex, matchCase, wholeWord, global) {
if (searchString === '') {
throw new Error('Cannot create regex from empty string');
}
if (!isRegex) {
searchString = searchString.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
}
if (wholeWord) {
if (!/\B/.test(searchString.charAt(0))) {
searchString = '\\b' + searchString;
}
if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
searchString = searchString + '\\b';
}
}
var modifiers = '';
if (global) {
modifiers += 'g';
}
if (!matchCase) {
modifiers += 'i';
}
return new RegExp(searchString, modifiers);
}
exports.createRegExp = createRegExp;
/**
* Create a regular expression only if it is valid and it doesn't lead to endless loop.
*/
function createSafeRegExp(searchString, isRegex, matchCase, wholeWord) {
if (searchString === '') {
return null;
}
// Try to create a RegExp out of the params
var regex = null;
try {
regex = createRegExp(searchString, isRegex, matchCase, wholeWord, true);
}
catch (err) {
return null;
}
// Guard against endless loop RegExps & wrap around try-catch as very long regexes produce an exception when executed the first time
try {
if (regExpLeadsToEndlessLoop(regex)) {
return null;
}
}
catch (err) {
return null;
}
return regex;
}
exports.createSafeRegExp = createSafeRegExp;
function regExpLeadsToEndlessLoop(regexp) {
// Exit early if it's one of these special cases which are meant to match
// against an empty string
if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$') {
return false;
}
// We check against an empty string. If the regular expression doesn't advance
// (e.g. ends in an endless loop) it will match an empty string.
var match = regexp.exec('');
return (match && regexp.lastIndex === 0);
}
exports.regExpLeadsToEndlessLoop = regExpLeadsToEndlessLoop;
/**
* Escapes regular expression characters in a given string
*/
function escapeRegExpCharacters(value) {
return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
}
exports.escapeRegExpCharacters = escapeRegExpCharacters;