简体   繁体   中英

How to check if a string contains url in java

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.

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

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
}

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM