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.

Community
  • 1
  • 1
Cataclysm
  • 7,592
  • 21
  • 74
  • 123

1 Answers1

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));
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • yes , thanks for great help. What is different between `String.matches("regex")`and `java.util.Pattern.compile('regex')` ? – Cataclysm Feb 26 '14 at 04:37
  • 2
    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: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html – aliteralmind Feb 26 '14 at 04:38
  • 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. – Cataclysm Feb 26 '14 at 04:43
  • 1
    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)`. – aliteralmind Feb 26 '14 at 04:44
  • 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 ? – Cataclysm Feb 26 '14 at 05:53