我只想從任何可能的字符串中建立一個正則表達式。 正則表達式
var usersString = "Hello?!*`~World()[]"; var expression = new RegExp(RegExp.escape(usersString)) var matches = "Hello".match(expression);
有內置的方法嗎? 若是沒有,人們會使用什麼? Ruby具備RegExp.escape
。 我以爲我不須要本身寫東西,那裏確定有一些標準。 謝謝! express
在jQueryUI的自動完成小部件(1.9.1版)中,他們使用略有不一樣的正則表達式(第6753行),這是將正則表達式與@bobince方法結合使用。 npm
RegExp.escape = function( value ) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }
這是一個較短的版本。 網絡
RegExp.escape = function(s) { return s.replace(/[$-\/?[-^{|}]/g, '\\$&'); }
這包括非元字符%
, &
, '
,和,
但JavaScript的正則表達式規範容許這樣作。 函數
Mozilla開發人員網絡正則表達式指南提供瞭如下轉義功能: this
function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }
其餘答案中的函數對於轉義整個正則表達式是過大的(它們對於轉義正則表達式的某些部分可能有用,這些正則表達式隨後將被合併爲更大的正則表達式)。 spa
若是您對整個正則表達式進行轉義並完成了此工做,則引用獨立的元字符( .
, ?
, +
, *
, ^
, $
, |
, \\
)或開始某些內容( (
, [
, {
) : prototype
String.prototype.regexEscape = function regexEscape() { return this.replace(/[.?+*^$|({[\\]/g, '\\$&'); };
是的,使人失望的是,JavaScript沒有這種內置函數。 code
對於使用lodash的任何人, 從v3.0.0開始,都內置了_.escapeRegExp函數: regexp
_.escapeRegExp('[lodash](https://lodash.com/)'); // → '\[lodash\]\(https:\/\/lodash\.com\/\)'