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 + "");
}
});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With