Regex to check with starts with http://, https:// or ftp://

后端 未结 5 1874
一个人的身影
一个人的身影 2020-12-28 12:59

I am framing a regex to check if a word starts with http:// or https:// or ftp://, my code is as follows,

     public          


        
5条回答
  •  死守一世寂寞
    2020-12-28 13:35

    I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:

    https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

    Taken from that page:

    import java.net.*;
    import java.io.*;
    
    public class ParseURL {
        public static void main(String[] args) throws Exception {
    
            URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                               + "/index.html?name=networking#DOWNLOADING");
    
            System.out.println("protocol = " + aURL.getProtocol());
            System.out.println("authority = " + aURL.getAuthority());
            System.out.println("host = " + aURL.getHost());
            System.out.println("port = " + aURL.getPort());
            System.out.println("path = " + aURL.getPath());
            System.out.println("query = " + aURL.getQuery());
            System.out.println("filename = " + aURL.getFile());
            System.out.println("ref = " + aURL.getRef());
        }
    }
    

    yields the following:

    protocol = http
    authority = example.com:80
    host = example.com
    port = 80
    path = /docs/books/tutorial/index.html
    query = name=networking
    filename = /docs/books/tutorial/index.html?name=networking
    ref = DOWNLOADING
    

提交回复
热议问题