1

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

user45678
  • 1,504
  • 6
  • 29
  • 58

5 Answers5

11

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);
user45678
  • 1,504
  • 6
  • 29
  • 58
3

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;
    }
6155031
  • 4,171
  • 6
  • 27
  • 56
0

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;
}
-1

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.

Sourabh86
  • 744
  • 10
  • 18
-2

You could match it using a regex.

Heres the Class in Android for using Regexes.

I quickly found this writeup on matching hashtags

And here's a SO question for matching URL's.

Community
  • 1
  • 1
Dan Schnau
  • 1,505
  • 14
  • 17