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

水深无声 2021-06-26 16:06 554阅读 0赞
  1. //业务需求:将网站URL地址进行截取,获得网站的主域名。
  2. //3种截取方式:切分,indexOf截取,正则表达式截取

代码如下:

  1. public class Test1 {
  2. public static void main(String[] args) {
  3. String Str = "http://www.baidu.com/free/play?chapterId=766";
  4. getStr1(Str);
  5. getStr2(Str);
  6. getStr3(Str);
  7. }
  8. private static void getStr1(String Str) {
  9. //切分
  10. String regex = "/";
  11. String[] strings = Str.split(regex);
  12. //输出结果
  13. System.out.println(strings[2]);
  14. }
  15. private static void getStr2(String Str) {
  16. String newStr = Str.replace("http://", "");
  17. String string = newStr.substring(0, newStr.indexOf("/"));
  18. System.out.println(string);
  19. }
  20. private static String getStr3(String Str) {
  21. Pattern pattern = Pattern.compile("[^http://]*?.com");
  22. Matcher matcher = pattern.matcher(Str);
  23. while(matcher.find()){
  24. String group = matcher.group();
  25. System.out.println(group);
  26. }
  27. return null;
  28. }
  29. }

输出结果:

  1. www.baidu.com

获取url的第一个/的路径

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using System.Web;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. namespace Pro
  9. {
  10. public partial class TEST : System.Web.UI.Page
  11. {
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. string imgurl = "http://img.com/5MA.jpg";
  15. Regex regex = new Regex(@"^(http|https):\/\/[^\/]*\/");
  16. Match match = regex.Match(imgurl);
  17. string oldimgurl = imgurl.Replace(match.Value, "");
  18. //Uri uri = new Uri(fs);
  19. //Response.Write(uri.AbsolutePath);
  20. Response.Write(oldimgurl);
  21. Response.End();
  22. }
  23. }
  24. }

发表评论

表情:
评论列表 (有 0 条评论,554人围观)

还没有评论,来说两句吧...

相关阅读