Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 853
Abhishek Avatar asked Nov 09 '11 06:11

Abhishek


People also ask

How do I check if a string starts with https?

To check if string starts with “http”, use PHP built-in function strpos(). strpos() takes the string and substring as arguments and returns 0, if the string starts with “http”, else not. This kind of check is useful when you want to verify if given string is an URL or not.

How do you match a URL in regex?

@:%_\+~#= , to match the domain/sub domain name. In this solution query string parameters are also taken care. If you are not using RegEx , then from the expression replace \\ by \ . Hope this helps.

Which method is used to test match in string regex?

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

How do I match a pattern in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

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)://.*$"));  
like image 60
Prince John Wesley Avatar answered Oct 17 '22 23:10

Prince John Wesley


Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")             || test.startsWith("https://")              || test.startsWith("ftp://"); 

I wouldn't be surprised if this is faster, too.

like image 40
Randall Cook Avatar answered Oct 17 '22 23:10

Randall Cook