1

I would like to check URL Validation in JAVA with regular-expression. I found this comment and I tried to use it in my code as follow...

private static final String PATTERN_URL = "/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)/";


.....
if (!urlString.matches(PATTERN_URL)) {
  System.err.println("Invalid URL");
  return false;
}

But I got compile time exception for writing my PATTERN_URL variable. I have no idea how to format it and I am worried about will it become invalid regex if I have modified. Can anyone fix it for me without losing original ? Thanks for your helps.

1 Answer 1

4

Your regex looks fine. You just need to format it for a Java string, by escaping all the escape-slashes:

\ --> \\

Resulting in this:

"/((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%@.\\w_]*)#?‌​(?:[\\w]*))?)/"

After Java interprets this string into a java.util.regex.Pattern, it will strip out those extra escape-slashes and become exactly the regex you want. You can prove this by printing it:

System.out.println(Pattern.compile(PATTERN_URL));
Sign up to request clarification or add additional context in comments.

5 Comments

yes , thanks for great help. What is different between String.matches("regex")and java.util.Pattern.compile('regex') ?
Not much, unless you need to do it over and over, then you'll want to go with the Pattern object, which avoids re-compiling the Pattern every iteration (this is what String.matches(s) does behind the scenes). See the "typical invocation" at the top of this page: docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
pls don't be mind , pls teach me what would be more preferable because my another validation methods also used with String.matches("regex") unless I have know exatly about it. Thanks.
If you're doing it over and over again, use Pattern and Matcher. If you're only doing it once per execution, for example, then stick with String.matches(s).
Now compile time error has fixed but validation result does not produce as expected.. what am I wrong ? It does no return true even mail.google.com. any suggestions ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.