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

Abhishek picture Abhishek · Nov 9, 2011 · Viewed 127.6k times · Source

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

     public static void main(String[] args) {
    try{
        String test = "http://yahoo.com";
        System.out.println(test.matches("^(http|https|ftp)://"));
    } finally{

    }
}

It prints false. I also checked stackoverflow post Regex to test if string begins with http:// or https://

The regex seems to be right but why is it not matching?. I even tried ^(http|https|ftp)\:// and ^(http|https|ftp)\\://

Answer

Prince John Wesley picture Prince John Wesley · Nov 9, 2011

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$"));