MAY3AM MAY3AM - 5 months ago 26
Android Question

Regular Expression - detect Specific Url and replace that string

I wanna detect exact domain

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

What I want:

this is sample text with one type of url mydomain.com/pin/123456. another type of url is mydomain.com/username.


Wel, I wrote this regex:

([Hh][tT][tT][pP][sS]?://)?(?:www\\.)?example\\.com/?.*

([Hh][tT][tT][pP][sS]?://)?(?:www\\.)?example\\.com/pin/?.*


this regex can detect:

http://www.example.com
https://www.example.com
www.example.com
example.com
Hhtp://www.example.com // and all other wrong type in http


with anything after
.com


Issues:

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

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

3. How to replace detected domain like
mydomain.com/pin/123
with
PostLink
and
mydomain.com/username
with
ProfileLink


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

Answer

With special thanks of Gildraths

Answer to question 1

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

Answer to question 2, 3

while(matcher.find()){

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

    if(contain){

        String profileId = matcher.group().substring(matcher.group().indexOf("/pin/") + 5, matcher.group().length());

    }

    // Answer to question 3 - replace match group with custom text
    textString = textString.replace(matcher.group(), "@" + 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);