Emulating SQL LIKE in JavaScript

后端 未结 9 1901
有刺的猬
有刺的猬 2020-11-30 05:56

How can I emulate the SQL keyword LIKE in JavaScript?

For those of you who don\'t know what LIKE is, it\'s a very simple regex which only s

相关标签:
9条回答
  • 2020-11-30 06:55

    An old question but there are actually no good answers here. TSQL LIKE expressions can contain square-bracket escaped sections that are already almost valid regular expressions and allow for matching % and _. E.g.:

    '75%' LIKE '75[%]'
    '[foo]' LIKE '[[]foo]' -- ugh
    

    Here's my function to convert a LIKE expression into a RegExp. The input is split into square-bracket and non-square-bracket sections. The square-bracket sections just need backslash escaping and the non-square-bracket sections are fully escaped while the % and _ directives are converted to regular expressions.

    const likeRegExp = (expression, caseSensitive = false) =>
        new RegExp(`^${
            expression.split(/(\[.+?\])/g)
            .map((s, i) => i % 2 ?
                s.replace(/\\/g, '\\\\') :
                s.replace(/[-\/\\^$*+?.()|[\]{}%_]/g, m => {
                    switch(m) {
                        case '%': return '.*';
                        case '_': return '.';
                        default: return `\\${m}`;
                    }
                })
            ).join('')
        }$`, caseSensitive ? '' : 'i');
    
    0 讨论(0)
  • 2020-11-30 07:00

    Here's a function I use, based on PHP's preg_quote function:

    function regex_quote(str) {
      return str.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1");
    }
    

    So your line would now be:

    var match = new RegEx(regex_quote(likeExpr).replace("%", ".*").replace("_", ".")).exec(str) != null;
    
    0 讨论(0)
  • 2020-11-30 07:00

    If you want to use a regex, you can wrap each character of the string in square-brackets. Then you only have a few characters to escape.

    But a better option might be to truncate the target strings so the length matches your search string and check for equality.

    0 讨论(0)
提交回复
热议问题