问题
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