2016-10-26 33 views
-1

我有以下的正则表达式,我已经验证:匹配的正则表达式零

"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?" 

enter image description here

我有以下的Javascript代码找到正则表达式:

var cTextVal = "This URL should match http://google.com"; 
var regEx = "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?" 


var matches = cTextVal.match(regEx); 
alert(matches); // This produces null 

如何在JavaScript中找到与此正则表达式匹配的字符串?

更新基于评论:

这崩溃我的代码:

var regEx = /(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?/g 

这会产生空:前第二捕获组

var regEx = "/(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?/g" 
+1

您需要使用'/ yourRegex /','没有 “yourRegex”',否则,你需要逃避反斜杠。 – Xufox

+1

或新的RegExp ....但在那种情况下转义\'s是一种痛苦 –

+0

如果有一个匹配项,它会在'matches [0]'',而不是基于'null结果。 – PHPglue

回答

0

逃生斜线

var regEx = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?/; 
 

 
var cTextVal = "This URL should match http://google.com"; 
 

 
var matches = cTextVal.match(regEx).shift(); 
 

 
console.log(matches);