NET中对url字符串中域名的三种截取方式

//业务需求:将网站URL地址进行截取,获得网站的主域名。 
//3种截取方式:切分,indexOf截取,正则表达式截取 

代码如下:

public class Test1 {
    public static void main(String[] args) {
        String Str = "http://www.baidu.com/free/play?chapterId=766";
        getStr1(Str);
        getStr2(Str);
        getStr3(Str);

    }

    private static void getStr1(String Str) {
        //切分
        String regex = "/";
        String[] strings = Str.split(regex);
        //输出结果
        System.out.println(strings[2]);
    }

    private static void getStr2(String Str) {
        String newStr = Str.replace("http://", "");
        String string = newStr.substring(0, newStr.indexOf("/"));
        System.out.println(string);
    }


    private static String getStr3(String Str) {
        Pattern pattern = Pattern.compile("[^http://]*?.com");
        Matcher matcher = pattern.matcher(Str);
        while(matcher.find()){
            String group = matcher.group();
            System.out.println(group);
        }
        return null;
    }
}

输出结果:

www.baidu.com

获取url的第一个/的路径

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Pro
{
    public partial class TEST : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string imgurl = "http://img.com/5MA.jpg";
            
            Regex regex = new Regex(@"^(http|https):\/\/[^\/]*\/");
            Match match = regex.Match(imgurl);
            string oldimgurl = imgurl.Replace(match.Value, "");
            //Uri uri = new Uri(fs);
            //Response.Write(uri.AbsolutePath);
            Response.Write(oldimgurl);
            Response.End();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值