为什么由 /.../ 创建的 javascript RegExp 可以工作,但通过“new RegExp”创建的相同内容却不能?

2023-12-11

我很困惑这里有什么区别以及为什么一个有效而另一个无效。有人可以解释一下吗?

//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 );

我究竟做错了什么?


\是转义字符strings。因此,要创建一个literal反斜杠作为转义字符常用表达,你需要转义它本身:

var regEx = new RegExp("(/\\*)", "g" );

如果您使用 Chrome 或 Safari(也许也在 Firebug 中),您可以通过在控制台中执行代码轻松查看结果表达式:

> new RegExp( "(/\*)", "g" );
/(/*)/g

> new RegExp( "(/\\*)", "g" );
/(/\*)/g

P.S.:不需要转义字符串中的斜杠(尽管它可能在正则表达式中被忽略)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么由 /.../ 创建的 javascript RegExp 可以工作,但通过“new RegExp”创建的相同内容却不能? 的相关文章