Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains url in java

Tags:

java

string

regex

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.

like image 985
Prithniraj Nicyone Avatar asked Nov 06 '25 20:11

Prithniraj Nicyone


2 Answers

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

like image 98
Anik Saha Avatar answered Nov 09 '25 09:11

Anik Saha


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
}
like image 40
whistling_marmot Avatar answered Nov 09 '25 10:11

whistling_marmot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!