user45678
user45678

Reputation: 1514

How to identify #hashtag and "http://" link from a string in android

is it possible to find a #hashtag and an "http://" link from a string and color it ? I am using this in Android.

public void setTitle(String title) {
    this.title = title;
}

Thanks in Advance

Upvotes: 1

Views: 4432

Answers (5)

6155031
6155031

Reputation: 4327

if you want to divide COMPOUND WORD into its parts.

from

#hashtag#hashtag2#hashtag3

to

{hashtag, hashtag2, hashtag3}

You can use this code below.

public static List<String> getHashTags(String str) {
        Pattern MY_PATTERN = Pattern.compile("(#[a-zA-Z0-9ğüşöçıİĞÜŞÖÇ]{2,50}\\b)");
        Matcher mat = MY_PATTERN.matcher(str);
        List<String> strs = new ArrayList<>();
        while (mat.find()) {
            strs.add(mat.group(1));
        }
        return strs;
    }

Upvotes: 3

Rohan Kumar
Rohan Kumar

Reputation: 1

This function will return a list of all the #hashtags in your string

public static List<String> getHashTags(String str) {
    Pattern MY_PATTERN = Pattern.compile("#(\\S+)");
    Matcher mat = MY_PATTERN.matcher(str);
    List<String> strs = new ArrayList<>();
    while (mat.find()) {
        strs.add(mat.group(1));
    }
    return strs;
}

Upvotes: 0

Sourabh86
Sourabh86

Reputation: 744

You can use Linkify class to do more than hashtag and webpages. Here is an example on how you can find hashtags in textview and link it to another activity.

Upvotes: -1

user45678
user45678

Reputation: 1514

I have found an answer and here is the way to do it :

        SpannableString hashtagintitle = new SpannableString(imageAndTexts1.get(position).getTitle());
        Matcher matcher = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashtagintitle);
        while (matcher.find())
        {
            hashtagintitle.setSpan(new ForegroundColorSpan(Color.BLUE), matcher.start(), matcher.end(), 0);

        }
        textView.setText(hashtagintitle);

Upvotes: 12

Related Questions