使用reg-ex捕获域名和网址?

时间:2017-03-17 03:57:45

标签: regex

我有一个以下字符串 -

1489713397.743 69 201.3.120.132 TCP_REFRESH_HIT/200 3013 GET http://www.google.com/manta/images/homepage/h_ftr-snapdata.gif pcallahan@google.com DIRECT/www.google.com - ALLOW_WBRS-DefaultGroup-Demo_Clients-NONE-NONE-DefaultRouting <IW_busi,6.5,-,-,-,-,-,-,-,-,-,-,-,-,-,IW_busi,-> - -

我想提取以下捕获组 - 用户,域和网址。

对于上面一行,它应该返回以下内容 -

User = pcallahan@google.com

Domain = http://www.google.com

网址= http://www.google.com/manta/images/homepage/h_ftr-snapdata.gif

2 个答案:

答案 0 :(得分:0)

假设您正在使用.NET,以下正则表达式应该提取您正在寻找的3个组:

(?<url>http://(?<domain>[^/]*)[^ ]*) (?<user>[^ ]*)

但是,只有当您的数据遵循我查看您提供的样本的假设时,这才有效。

答案 1 :(得分:0)

这是javascript中的正则表达式。您需要使用组匹配来完成所有操作:

&#13;
&#13;
var str="1489713397.743 69 201.3.120.132 TCP_REFRESH_HIT/200 3013 GET http://www.google.com/manta/images/homepage/h_ftr-snapdata.gif pcallahan@google.com DIRECT/www.google.com - ALLOW_WBRS-DefaultGroup-Demo_Clients-NONE-NONE-DefaultRouting <IW_busi,6.5,-,-,-,-,-,-,-,-,-,-,-,-,-,IW_busi,-> - -";


var rgx= /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b)([-a-zA-Z0-9@:%_\+.~#?&//=]*)?/ig

var match = rgx.exec(str);

if (match){
console.log(match[0]); // the entire url
match[1] && console.log(match[1]); // onyl the domain

}
&#13;
&#13;
&#13;

以下是javascript中的正则表达式:

(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b)([-a-zA-Z0-9@:%_\+.~#?&//=]*)/ig

现在这是一个例子: