我只是想从任何可能的字符串中创建一个正则表达式。

var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);

有内置的方法吗?如果不是,人们用什么?Ruby有RegExp.escape。我觉得我不需要写我自己的,必须有一些标准的东西。


当前回答

这是长久之计。

function regExpEscapeFuture(literal_string) {
     return literal_string.replace(/[^A-Za-z0-9_]/g, '\\$&');
}

其他回答

没有什么可以阻止你转义每个非字母数字字符:

usersString.replace(/(?=\W)/g, '\\');

在执行re.toString()时,您会损失一定程度的可读性,但您获得了极大的简单性(和安全性)。

根据ECMA-262,一方面,正则表达式“语法字符”总是非字母数字的,这样的结果是安全的,特殊转义序列(\d, \w, \n)总是字母数字的,这样就不会产生错误的控制转义。

在jQuery UI的自动完成小部件(版本1.9.1)中,他们使用了一个略有不同的正则表达式(第6753行),下面是正则表达式与bobince方法的结合。

RegExp.escape = function( value ) {
     return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}

刚刚发布了一个基于RegExp.escape shim的regex转义要点,而RegExp.escape shim又是基于被拒绝的RegExp.escape提议的。看起来大致相当于公认的答案,除了它没有转义-字符,根据我的手动测试,这似乎实际上是好的。

撰写本文时的主要内容:

const syntaxChars = /[\^$\\.*+?()[\]{}|]/g

/**
 * Escapes all special special regex characters in a given string
 * so that it can be passed to `new RegExp(escaped, ...)` to match all given
 * characters literally.
 *
 * inspired by https://github.com/es-shims/regexp.escape/blob/master/implementation.js
 *
 * @param {string} s
 */
export function escape(s) {
  return s.replace(syntaxChars, '\\$&')
}

我借用了上面bobince的答案,创建了一个带标签的模板函数,用于创建RegExp,其中部分值被转义,部分值不被转义。

regex-escaped.js

RegExp.escape = text => text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); RegExp.escaped = flags => function (regexStrings, ...escaped) { const source = regexStrings .map((s, i) => // escaped[i] will be undefined for the last value of s escaped[i] === undefined ? s : s + RegExp.escape(escaped[i].toString()) ) .join(''); return new RegExp(source, flags); }; function capitalizeFirstUserInputCaseInsensitiveMatch(text, userInput) { const [, before, match, after ] = RegExp.escaped('i')`^((?:(?!${userInput}).)*)(${userInput})?(.*)$`.exec(text); return `${before}${match.toUpperCase()}${after}`; } const text = 'hello (world)'; const userInput = 'lo (wor'; console.log(capitalizeFirstUserInputCaseInsensitiveMatch(text, userInput));

对于TypeScript的粉丝们…

global.d.ts

interface RegExpConstructor {
  /** Escapes a string so that it can be used as a literal within a `RegExp`. */
  escape(text: string): string;

  /**
   * Returns a tagged template function that creates `RegExp` with its template values escaped.
   *
   * This can be useful when using a `RegExp` to search with user input.
   *
   * @param flags The flags to apply to the `RegExp`.
   *
   * @example
   *
   * function capitalizeFirstUserInputCaseInsensitiveMatch(text: string, userInput: string) {
   *   const [, before, match, after ] =
   *     RegExp.escaped('i')`^((?:(?!${userInput}).)*)(${userInput})?(.*)$`.exec(text);
   *
   *   return `${before}${match.toUpperCase()}${after}`;
   * }
   */
  escaped(flags?: string): (regexStrings: TemplateStringsArray, ...escapedVals: Array<string | number>) => RegExp;
}

Mozilla开发者网络正则表达式指南提供了这个转义函数:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}