复制Java的“Pattern.quote”的功能。在一个JavaScript的RegExp [英] Replicate the functionality of Java's "Pattern.quote" in a JavaScript RegExp
问题描述
Pattern.compile(stackoverflow.com)来匹配URL stackoverflow.com
的正则表达式。 )
。但这是错误的,因为。
在正则表达式中有特殊含义。解决这个问题的最简单的方法是写出 Pattern.compile(Pattern.quote(stackoverflow.com))
,它出现在: Pattern中。编译(\\Qstackoverflow.com\\\E)
其中quotes整个字符串。 我想在JavaScript中做同样的事情,但JavaScript的正则表达式不会为<$ c $ c> \ Q 和 \E
,它看起来不像是JavaScript的等价物,所以我不知道如何去做。我的第一个想法(请参阅下面的答案)是在JavaScript正则表达式中,在任何具有特殊含义的字符前面加一个反斜杠,但这似乎有潜在的错误倾向,我怀疑有人可能知道更好的方法。 >
这是一个Firefox扩展,所以特定于Mozilla的解决方案是可以的。
详细说明我的建议,它看起来像这样:
// RegExp匹配所有的字符有一个RegExp
中的特殊含义var regexpSpecialChars = /([\ [\] \ ^ \ $ \ | \(\)\\\\\\\\\\\\\\\\\\\\\\\\\\' !\\ {\} \ = \])/ GI;
我不确定这是否正确,因为某些字符(如!
和 =
)在某些情况下似乎只有特殊的含义。但假设它是,那么你会做
$ b $ pre $ var $ quotedURL = url.replace(regexpSpecialChars,'\\ $ 1' );
来取代所有 $
用 \ $
的。然后你可以从 quotedURL
:
var myRegExp =新的RegExp(quotedURL,'gi');
In Java, you might try to make a regular expression that would match the URL stackoverflow.com
using Pattern.compile("stackoverflow.com")
. But this would be wrong because the .
has special meaning in regular expressions. The easiest way to fix this is to write Pattern.compile(Pattern.quote("stackoverflow.com"))
which comes out to: Pattern.compile("\\Qstackoverflow.com\\E")
which "quotes" the entire string.
I want to do the same thing in JavaScript, but JavaScript's regular expressions don't assign any meaning to \Q
and \E
and it doesn't look like there is a JavaScript equivalent, so I'm not sure how to go about it. My first thought (see my answer below) is to just put a backslash before any character that has a special meaning in a JavaScript regex, but this seems potentially error-prone and I suspect that someone might know of a better way.
This is for a Firefox extension so Mozilla-specific solutions are okay.
To elaborate on my suggestion, it would look something like this:
// A RegExp that matches all the characters which have a special meaning in a RegExp
var regexpSpecialChars = /([\[\]\^\$\|\(\)\\\+\*\?\{\}\=\!])/gi;
I'm not sure if this is quite right, since some characters (like !
and =
) only seem to have special meaning in certain situations. But assuming that it is, then you would do
var quotedURL = url.replace(regexpSpecialChars, '\\$1');
to replace, for instance, all $
's with \$
's. Then you can just build the RegExp from quotedURL
:
var myRegExp = new RegExp(quotedURL, 'gi');
这篇关于复制Java的“Pattern.quote”的功能。在一个JavaScript的RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!