Excel Vba 正則URL協議、網域名稱、連接埠號碼、頁面路徑

來源:互聯網
上載者:User

開啟Excel,Shift + F11 開啟VBA編輯器,注意高度時必須先儲存,否則會提示無法高度外部程式。

Sub RegexURL()

Dim url As String
Dim regex As Object
url = "http://www.baidu.com/a/b/index.html"
Set regex = CreateObject("vbscript.regexp")
regex.Global = True
regex.Pattern = "(\w+)://([^/:]+)(:\d*)?([^# ]*)"
MsgBox regex.Replace(url, "使用協議/主網域名稱/連接埠號碼/頁面:[$1],[$2],[$3],[$4]")

End Sub
            Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)");

List<string> items = new List<string>() {
"http://www.baidu.com",
"http://www.baidu.com/index.html",
"http://www.fengcao.baidu.cn/index/index.html",
"ftp://www.baidu.cn/index/index.html",
"ftp://www.baidu.com.cn",
"http://www.net.cn",
};

StringBuilder sb = new StringBuilder ();
foreach (string item in items)
{
foreach(Match match in reg.Matches(item))
{
//for(int i=0;i<match.Groups.Count ;i++)
//{
//sb.Append(match.Groups[2]);
MessageBox.Show(GetServerDomain(match.Groups[2].ToString ()));
//}
}
sb.AppendLine("--");
}

string result = sb.ToString();
       public bool IsNumeric(string str)
{
try { int i = Convert.ToInt32(str); return true; }
catch { return false; }
}

public string GetServerDomain(string url)
{
string str = url.ToLower();//此處擷取值轉換為小寫
if (str.IndexOf('.') > 0)
{
string[] strArr = str.Split('.');
string lastStr = strArr.GetValue(strArr.Length - 1).ToString();
if (IsNumeric(lastStr)) //如果最後一位是數字,那麼說明是IP地址
{
return str.Replace(".", ""); //替換.為純數字輸出
}
else //否則為網域名稱
{
string[] domainRules = ".com.cn|.net.cn|.org.cn|.gov.cn|.com|.net|.cn|.org|.cc|.me|.tel|.mobi|.asia|.biz|.info|.name|.tv|.hk|.公司|.中國|.網路".Split('|');
string findStr = string.Empty;
string replaceStr = string.Empty;
string returnStr = string.Empty;
for (int i = 0; i < domainRules.Length; i++)
{
if (str.EndsWith(domainRules[i].ToLower())) //如果最後有找到匹配項
{
findStr = domainRules[i].ToString(); //www.eieboom.com
replaceStr = str.Replace(findStr, ""); //將匹配項替換為空白,便於再次判斷
if (replaceStr.IndexOf('.') > 0) //存在次層網域或者三級,比如:www.eieboom
{
string[] replaceArr = replaceStr.Split('.'); // www eieboom
returnStr = replaceArr.GetValue(replaceArr.Length - 1).ToString() + findStr;
return returnStr;
}
else //eieboom
{
returnStr = replaceStr + findStr; //串連起來輸出為:eieboom.com
return returnStr;
};
}
else
{ returnStr = str; }
}
return returnStr;
}
}
else
{
return str;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.