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)\\://
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.
@:%_\+~#= , 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.
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.
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).
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)://.*$"));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With