如何正确转义正则表达式中的字符 [英] How to properly escape characters in regexp
问题描述
我想在字符串中进行字符串搜索。简单地说 MySTR.search(Needle)
。
I want to do a string search inside a string. Simply saying MySTR.search(Needle)
.
当这个针
string包含特殊的正则表达式字符,如*,+等等。它失败,错误无效量词
。
The problem occurs when this needle
string contains special regex characters like *,+ and so on. It fails with error invalid quantifier
.
我已浏览网页,发现该字符串可以转义为 \Q一些字符串\E
。
I have browsed the web and found out that string can be escaped with \Q some string \E
.
但是,这并不总是产生所需的行为。例如:
However, this does not always produce the desired behavior. For example:
var sNeedle = '*Stars!*';
var sMySTR = 'The contents of this string have no importance';
sMySTR.search('\Q' + sNeedle + '\E');
结果为-1。 OK。
var sNeedle = '**Stars!**';
var sMySTR = 'The contents of this string have no importance';
sMySTR.search('\Q' + sNeedle + '\E');
结果是无效的量词。这是因为两个或更多的特殊字符彼此触摸,因为:
Result is "invalid quantifier". This happens because 2 or more special characters are 'touching' each other, because:
var sNeedle = '*Dont touch me*Stars!*Dont touch me*';
var sMySTR = 'The contents of this string have no importance';
sMySTR.search('\Q' + sNeedle + '\E');
可以正常工作。
我知道我可以在每个可能的特殊正则表达式字符之前添加一个函数 escapeAllBadChars(sInStr)
,然后添加双斜杠,但我想知道是否有更简单的方法? / p>
I know I could make a function escapeAllBadChars(sInStr)
and just add double slashes before every possible special regex character, but I'm wondering if there is a simpler way to do it?
推荐答案
\Q ... \E
不工作在JavaScript中(至少他们不会逃避任何东西...),你可以看到:
\Q...\E
doesn't work in JavaScript (at least, they don't escape anything...) as you can see:
var s = "*";
print(s.search(/\Q*\E/));
print(s.search(/\*/));
产生:
-1
0
正如您可以在 Ideone 。
需要转义以下字符:
-
(
-
)
-
[
-
-
*
-
-
。
-
$
-
^
-
\\
-
|
-
?
(
)
[
{
*
+
.
$
^
\
|
?
所以,这样做会:
function quote(regex) {
return regex.replace(/([()[{*+.$^\\|?])/g, '\\$1');
}
不,]
和}
不需要转义:他们没有特殊的意义,只有他们的开放柜台部分。
No, ]
and }
don't need to be escaped: they have no special meaning, only their opening counter parts.
请注意,当使用文字正则表达式 /.../
时,您还需要转义 /
char。但是, /
不是正则表达式元字符:在 RegExp
对象中使用它时,它不需要逃逸。
Note that when using a literal regex, /.../
, you also need to escape the /
char. However, /
is not a regex meta character: when using it in a RegExp
object, it doesn't need an escape.
这篇关于如何正确转义正则表达式中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!