Table: Matches column names with unescaped regex characters (#21164)

* Table: Matches column names with unescaped regex characters
Fixes #21106

* Chore: Cleans up unused code
This commit is contained in:
Hugo Häggmark
2019-12-18 12:38:39 +01:00
committed by GitHub
parent 26aa1f0cca
commit 05cb85feba
6 changed files with 144 additions and 59 deletions

View File

@@ -1,6 +1,11 @@
import { stringToJsRegex, stringToMs } from './string';
import { escapeStringForRegex, stringToJsRegex, stringToMs, unEscapeStringFromRegex } from './string';
describe('stringToJsRegex', () => {
it('should just return string as RegEx if it does not start as a regex', () => {
const output = stringToJsRegex('validRegexp');
expect(output).toBeInstanceOf(RegExp);
});
it('should parse the valid regex value', () => {
const output = stringToJsRegex('/validRegexp/');
expect(output).toBeInstanceOf(RegExp);
@@ -51,3 +56,35 @@ describe('stringToMs', () => {
}).toThrow();
});
});
describe('escapeStringForRegex', () => {
describe('when using a string with special chars', () => {
it('then all special chars should be escaped', () => {
const result = escapeStringForRegex('([{}])|*+-.?<>#&^$');
expect(result).toBe('\\(\\[\\{\\}\\]\\)\\|\\*\\+\\-\\.\\?\\<\\>\\#\\&\\^\\$');
});
});
describe('when using a string without special chars', () => {
it('then nothing should change', () => {
const result = escapeStringForRegex('some string 123');
expect(result).toBe('some string 123');
});
});
});
describe('unEscapeStringFromRegex', () => {
describe('when using a string with escaped special chars', () => {
it('then all special chars should be unescaped', () => {
const result = unEscapeStringFromRegex('\\(\\[\\{\\}\\]\\)\\|\\*\\+\\-\\.\\?\\<\\>\\#\\&\\^\\$');
expect(result).toBe('([{}])|*+-.?<>#&^$');
});
});
describe('when using a string without escaped special chars', () => {
it('then nothing should change', () => {
const result = unEscapeStringFromRegex('some string 123');
expect(result).toBe('some string 123');
});
});
});

View File

@@ -1,6 +1,32 @@
const specialChars = ['(', '[', '{', '}', ']', ')', '|', '*', '+', '-', '.', '?', '<', '>', '#', '&', '^', '$'];
export const escapeStringForRegex = (value: string) => {
if (!value) {
return value;
}
return specialChars.reduce((escaped, currentChar) => escaped.replace(currentChar, '\\' + currentChar), value);
};
export const unEscapeStringFromRegex = (value: string) => {
if (!value) {
return value;
}
return specialChars.reduce((escaped, currentChar) => escaped.replace('\\' + currentChar, currentChar), value);
};
export function stringStartsAsRegEx(str: string): boolean {
if (!str) {
return false;
}
return str[0] === '/';
}
export function stringToJsRegex(str: string): RegExp {
if (str[0] !== '/') {
return new RegExp('^' + str + '$');
if (!stringStartsAsRegEx(str)) {
return new RegExp(`^${str}$`);
}
const match = str.match(new RegExp('^/(.*?)/(g?i?m?y?)$'));