在JavaScript中匹配URL的正则表达式生成null

时间:2016-10-26 00:41:03

标签: javascript regex

我有以下正式表达式,我已经验证过:

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

enter image description here

我有以下Javascript代码来查找正则表达式:

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


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

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

根据评论更新:

这会导致我的代码崩溃:

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

这会产生null:

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

1 个答案:

答案 0 :(得分:0)

在第二个捕获组之前向前转义斜杠



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

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

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

console.log(matches);