Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all hashtags from EditText

I have an EdiText. User can mention hashtags in it. I want to get those hashtags and add them to an ArrayList. How can I get those hashtags from EdiText.

Suppose my edittxtmsg contains #Stackoverflow slove me #hashtag #problem

I want these hashtags: #Stackoverflow #hashtag #problem

edittxtmsg.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub

                    int strLenght = s.toString().length();
                    int available = 140 - strLenght;
                    setAvailableSpace(available);
                    if (available < 0) {
                        s.delete(strLenght - 1, strLenght);
                    }
                    mfinalmsg = s.toString();


                }

                private void setAvailableSpace(int available) {
                    // TODO Auto-generated method stub
                    tvcount.setText(available + "");
                }
            });
like image 342
Sree Reddy Menon Avatar asked Oct 29 '14 13:10

Sree Reddy Menon


2 Answers

You can use Regular Expression to get all hashtags from EditText:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String text = editText.getText().toString();
String regexPattern = "(#\\w+)";

Pattern p = Pattern.compile(regexPattern);
Matcher m = p.matcher(text);
while (m.find()) {
    String hashtag = m.group(1);
    // Add hashtag to ArrayList
    ...
}

(#\\w+) matches all hashtags that start with #.

This one is also fast.

enter image description here

like image 168
Coder Avatar answered Nov 16 '22 17:11

Coder


String text = editText.getText().toString();
String[] words = text.split(" ");    
List<String> tags = new ArrayList<String>();

for ( String word : words) {
    if (word.substring(0, 1).equals("#")) {
        tags.add(word);    
    }
}

Gets the text from editText, splits it into seperate words, creates a list of all words that start with #

As Yazan mentioned, a good alternative to if (word.substring(0, 1).equals("#") is if (word.startsWith("#")

Timing

enter image description here

like image 29
Tim Avatar answered Nov 16 '22 17:11

Tim