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)\\://
If you wanna do it in case-insensitive way, this is better:
Unless there is some compelling reason to use a regex, I would just use String.startsWith:
I wouldn't be surprised if this is faster, too.
You need a whole input match here.
Edit:(Based on @davidchambers's comment)
test.matches() method checks all text.use test.find()
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:
yields the following: