3

If I have a string like below :

String str = "Google is awesome search engine. https://www.google.co.in";

Now in the above string I need to check if the string contains any link or not. In the above string it should return true as the string contains a link.

The function should check www.google.com also as link. It should not dependent on http:// or https://

I have checked this link also What's the best way to check if a String contains a URL in Java/Android? But it is returning true only if the string contain url only and what I want is if a string contain link at any place, it should return true.

I want that string also which will match the pattern, so that I can set that in a textview in android and can make it clickable.

How can I do this, please help me.

Community
  • 1
  • 1
Prithniraj Nicyone
  • 5,021
  • 13
  • 52
  • 78
  • Possible duplicate of [What's the best way to check if a String contains a URL in Java/Android?](http://stackoverflow.com/questions/11007008/whats-the-best-way-to-check-if-a-string-contains-a-url-in-java-android) – user902383 Dec 07 '15 at 13:53

3 Answers3

3

The regex is

((http:\/\/|https:\/\/)?(www.)?(([a-zA-Z0-9-]){2,}\.){1,4}([a-zA-Z]){2,6}(\/([a-zA-Z-_\/\.0-9#:?=&;,]*)?)?)

Check this link for more information

Community
  • 1
  • 1
Anik Saha
  • 4,313
  • 2
  • 26
  • 41
  • what's the use of `{1,4}` there, cannot you have something like `ti.com`, what happens with first level domain `barcelona` (it has more than six letters)? I think there are a lot of valid urls that will not match your regex. What about internationalized domains? – Luis Colorado Dec 09 '15 at 05:39
1

You could split the string on spaces and then test each 'word' in the resultant array using one of the methods in the answer you linked to above.

String[] words = str.split(" ");
for (String word : words) {
    // test here using your favourite methods from the linked answer
}
Community
  • 1
  • 1
whistling_marmot
  • 3,561
  • 3
  • 25
  • 39
0

The easiest way is to use indexOf method. Like:

String target =" test http://www.test1.com";
String http = "http:";
System.out.println(target.indexOf(http));

Or, you can use Regular Expressions:

String target ="test http://www.test1.com";
String http = "((http:\\/\\/|https:\\/\\/)?(www.)?(([a-zA-Z0-9-]){2,}\\.){1,4}([a-zA-Z]){2,6}(\\/([a-zA-Z-_\\/\\.0-9#:?=&;,]*)?)?)";
Pattern pattern = Pattern.compile(http);
Matcher matcher = pattern.matcher(target);
while (matcher.find()) {
    System.out.println(matcher.start() + " : " + matcher.end());
}
iviorel
  • 312
  • 3
  • 10