2016-10-26 34 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);