4

Possible Duplicates:
What is the best regular expression to check if a string is a valid URL
Java-How to detect the presence of URL in a string.

Is there a way to see if a string is a valid URL? I'm using MIDP library and there are not regular expressions in MIDP. Any help is greatly appreciated.

Community
  • 1
  • 1
user69514
  • 24,321
  • 56
  • 146
  • 183
  • please search the site before posting, "java regex url" returns plenty of valid information. – Mat Apr 19 '11 at 20:21
  • Note that searching "java regex url" would direct you to use a regex to detect a URL, when the better solution would be missed: construct a java.net.URL from the string. – Edwin Buck Apr 19 '11 at 20:23
  • 1
    If everything is an exact duplicate, then why bother answering any question on SO? – Edwin Buck Apr 19 '11 at 20:25
  • Java.net is not a library in java mobile edition. J2ME doesn't not have Java.Net library, neither does it support regex or String.replaceAll – user69514 Apr 19 '11 at 20:26
  • @Edwin: that's suggested in the top answers to such questions. – Mat Apr 19 '11 at 20:27
  • Thank you, i didn't know about the lack of URL support in JavaME. I'll ammend my answer for the ME crowd, after I construct a better one. – Edwin Buck Apr 19 '11 at 20:27
  • @Mat, perhaps it is, but that's because it's an obvious answer. I'll bet that you and I can come up with independent answers to x + 4 = 5 without need for copying from each other; but, if only the first poster gets to benefit from such a task, then there's no reason to answer anything with an archive like SO's. – Edwin Buck Apr 19 '11 at 20:31
  • @Edwin: I'm only pointing out the fact that by typing the first three tags from this person's question in the search box, there was a wealth of info already available. if none of that is relevant to the OP, then his question needs to be more specific. – Mat Apr 19 '11 at 20:33

1 Answers1

16

Why not just construct a java.net.URL out of the string and catch any exceptions that might be thrown?

String something;
try {
  URL url = new URL(something);
} catch (MalformedURLException e) {
  // it wasn't a URL
}
Edwin Buck
  • 64,804
  • 7
  • 90
  • 127
  • is it also required to call .toURI() ? – Gaurav May 19 '21 at 07:50
  • 1
    @Gaurav Only if you need a URI type. If all you need is a URL, then creating the URL will do. Note that it's not a good idea to create a URI if you need a URL, because URIs contain all URLs and other element (URNs, for example) and anyone that built a URN might break code that assumes URIs are just URLs. Note that this only validates the format, but that's all that can be validated until the URL is used. – Edwin Buck May 19 '21 at 13:57