javaregexstartswith

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


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)\\://


Solution

  • 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)://.*$"));