//业务需求:将网站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();
}
}
}