为什么/.../创建的javascript RegExp工作,但是通过“new RegExp”创建的相同才不是? [英] Why does a javascript RegExp created by /.../ work but the same created via "new RegExp" does not?
问题描述
我很困惑这里的区别是什么,为什么一个有效,另一个没有。有人可以解释一下吗?
//搜索
的字符串var str =这是一个字符串/ *有些东西在这里;
//这个不起作用,它警告一个空的匹配
var regEx = new RegExp(((\ / \ *),g);
//这个也不起作用(以防万一转移是问题)
var regEx2 = new RegExp((/ *),g);
//这一个工作
var regEx3 = /(\ / \ *)/ g;
var match = null;
//尝试第一个,它会警告,
if(match = regEx.exec(str))alert(match);
//尝试第二个,它会警告,
if(match = regEx2.exec(str))alert(match);
//尝试第三个,它提醒/ *,/ * - 它有效!
if(match = regEx3.exec(str))alert(match);
我做错了什么?
\
是字符串中的转义字符。因此,要为正则表达式创建文字反斜杠作为转义字符,您需要将其自身转义:
var regEx = new RegExp((/ \\ *),g);
如果您使用Chrome或Safari(也可能在Firebug中),您可以轻松查看结果表达式在控制台中执行代码:
>
new RegExp((/ \ *),g );
/(/ *)/ g
< p >>新的RegExp((/ \\ *),g);
/( / \ *)/ g
PS:无需转义字符串中的斜杠(尽管在正则表达式中可能会被忽略。
I'm confused as to what the difference here is and why one works and the other does not. Can someone explain this?
//The string to search through
var str = "This is a string /* with some //stuff in here";
//This one will NOT work, it alerts an empty "match"
var regEx = new RegExp( "(\/\*)", "g" );
//This one also will NOT work (tried just in case escaping was the issue)
var regEx2 = new RegExp( "(/*)", "g" );
//This one DOES work
var regEx3 = /(\/\*)/g;
var match = null;
//Trying the first one, it alerts ","
if ( match = regEx.exec( str ) ) alert( match );
//Trying the second one, it alerts ","
if ( match = regEx2.exec( str ) ) alert( match );
//Trying the third one, it alerts "/*,/*" - it works!
if ( match = regEx3.exec( str ) ) alert( match );
What am I doing wrong?
\
is the escape characters in strings. Hence, to create a literal backslash as escape character for the regular expressions, you need to escape it itself:
var regEx = new RegExp("(/\\*)", "g" );
If you use Chrome or Safari (maybe also in Firebug), you can easily see the resulting expression by executing the code in the console:
>
new RegExp( "(/\*)", "g" );
/(/*)/g
>
new RegExp( "(/\\*)", "g" );
/(/\*)/g
P.S.: No need to escape the slash in the string (though it might be ignored in the regex).
这篇关于为什么/.../创建的javascript RegExp工作,但是通过“new RegExp”创建的相同才不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!