Get all hashtags from EditText

妖精的绣舞 提交于 2020-02-23 02:09:32

问题


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 + "");
                }
            });

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/26631910/get-all-hashtags-from-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!