Getting parts of a URL (Regex)

后端 未结 26 2531
说谎
说谎 2020-11-22 02:13

Given the URL (single line):
http://test.example.com/dir/subdir/file.html

How can I extract the following parts using regular expressions:

  1. The Subd
26条回答
  •  一整个雨季
    2020-11-22 03:00

    String s = "https://www.thomas-bayer.com/axis2/services/BLZService?wsdl";
    
    String regex = "(^http.?://)(.*?)([/\\?]{1,})(.*)";
    
    System.out.println("1: " + s.replaceAll(regex, "$1"));
    System.out.println("2: " + s.replaceAll(regex, "$2"));
    System.out.println("3: " + s.replaceAll(regex, "$3"));
    System.out.println("4: " + s.replaceAll(regex, "$4"));
    

    Will provide the following output:
    1: https://
    2: www.thomas-bayer.com
    3: /
    4: axis2/services/BLZService?wsdl

    If you change the URL to
    String s = "https://www.thomas-bayer.com?wsdl=qwerwer&ttt=888"; the output will be the following :
    1: https://
    2: www.thomas-bayer.com
    3: ?
    4: wsdl=qwerwer&ttt=888

    enjoy..
    Yosi Lev

提交回复
热议问题