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

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

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


当前回答

另一种(更安全的)方法是使用unicode转义格式\u{code}转义所有字符(而不仅仅是我们目前知道的一些特殊字符):

function escapeRegExp(text) {
    return Array.from(text)
           .map(char => `\\u{${char.charCodeAt(0).toString(16)}}`)
           .join('');
}

console.log(escapeRegExp('a.b')); // '\u{61}\u{2e}\u{62}'

请注意,你需要传递u标志来让这个方法工作:

var expression = new RegExp(escapeRegExp(usersString), 'u');

其他回答

escapeRegExp = function(str) {
  if (str == null) return '';
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

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

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

在另一个答案中链接的函数是不够的。它不能转义^或$(字符串的开始和结束),或-,在字符组中用于范围。

使用这个函数:

function escapeRegex(string) {
    return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}

虽然乍一看似乎没有必要,但转义-(以及^)使函数适合转义插入字符类以及正则表达式体中的字符。

转义/使函数适合转义在JavaScript正则表达式文字中使用的字符,以供以后计算。

由于转义它们都没有任何缺点,因此转义以覆盖更广泛的用例是有意义的。

是的,这不是标准JavaScript的一部分,这是一个令人失望的失败。

在https://github.com/benjamingr/RexExp.escape/上有一个RegExp.escape的ES7提议,在https://github.com/ljharb/regexp.escape上有一个polyfill可用。

一个基于被拒绝的ES提案的例子,包括检查属性是否已经存在,以防TC39改变他们的决定。


代码:

if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
  RegExp.escape = function(string) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
    // https://github.com/benjamingr/RegExp.escape/issues/37
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
}

代码简化:

Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")});

// ...
var assert = require('assert');
 
var str = 'hello. how are you?';
var regex = new RegExp(RegExp.escape(str), 'g');
assert.equal(String(regex), '/hello\. how are you\?/g');

还有一个npm模块在: https://www.npmjs.com/package/regexp.escape


你可以安装这个并这样使用它:


npm install regexp.escape

or

yarn add regexp.escape

var escape = require('regexp.escape');
var assert = require('assert');
 
var str = 'hello. how are you?';
var regex = new RegExp(escape(str), 'g');
assert.equal(String(regex), '/hello\. how are you\?/g');

在GitHub && NPM页面是如何使用shim/polyfill这个选项的描述。该逻辑基于返回regexp .escape || implementation;,其中实现包含上面使用的regexp。


NPM模块是一个额外的依赖项,但它也使外部贡献者更容易识别添加到代码中的逻辑部分。¯\()/¯

XRegExp有一个转义函数:

XRegExp.escape(“逃?< >。'); // -> '已转义\?\ < \ >。”

更多信息:http://xregexp.com/api/#escape