本文介绍了在JavaScript中模拟SQL LIKE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中模拟SQL关键字 LIKE

How can I emulate the SQL keyword LIKE in JavaScript?

对于那些不这样做的人知道 LIKE 是什么,这是一个非常简单的正则表达式,只支持通配符,匹配0个或更多字符,和 _ 只匹配一个字符。

For those of you who don't know what LIKE is, it's a very simple regex which only supports the wildcards %, which matches 0 or more characters, and _ which matches exactly one character.

但是,它不仅可以做类似的事情:

However, it's not just possible to do something like:

var match = new RegEx(likeExpr.replace("%", ".*").replace("_", ".")).exec(str) != null;

...因为模式可能包含点,星号和任何其他特殊的正则表达式字符。

...because the pattern might contain dots, stars and any other special regex characters.

推荐答案

只要您第一次逃避模式中的正则表达式字符,您所拥有的将会起作用。以下是中的一个示例:

What you have will work as long as you first escape the regex characters in your pattern. Below is one example from Simon Willison’s blog:

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

然后您可以将代码实现为:

You could then implement your code as:

likeExpr = RegExp.escape(likeExpr);
var match = new RegEx(likeExpr.replace("%", ".*").replace("_", ".")).exec(str) != null;

这篇关于在JavaScript中模拟SQL LIKE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 21:40