MAY3AM MAY3AM - 1 year ago 134
Android Question

Regular Expression - detect Specific Url and replace that string

I wanna detect exact domain

in string and then change that with another string and finally make it clickable in

What I want:

this is sample text with one type of url another type of url is

Wel, I wrote this regex:



this regex can detect:
Hhtp:// // and all other wrong type in http

with anything after


1. How detect end of domain ( with space or dot)

2. How detect two type of domain, one with
and another without?

3. How to replace detected domain like

4. I know how to make them clickable with
but if it possible show me best way to provide content provider for links to open each link with proper activity

Answer Source

With special thanks of Gildraths

Answer to question 1

String urlRegex = "(https?://)?(?:www\\.)?[\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?";
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(textString);

Answer to question 2, 3


    // Answer to question 2 - If was true, url contain "/pin"
    boolean contain ="/pin/") >= 0;


        String profileId ="/pin/") + 5,;


    // Answer to question 3 - replace match group with custom text
    textString = textString.replace(, "@" + profileId);

Answer to question 4

// Pattern to detect replaced custom text
Pattern profileLink     = Pattern.compile("[@]+[A-Za-z0-9-_]+\\b");

// Schema
String Link             = "content://"+Context.getString(R.string.profile_authority)+"/";

// Make it linkify ;)
Linkify.addLinks(textView, profileLink, Link);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download