EditText 输入控制,用InputFilter过滤表情、特殊字符

时间:2022-04-04 10:05:27
  /**
* 过滤掉常见特殊字符,常见的表情
*/
public static void setEtFilter(EditText et) {
if (et == null) {
return;
}
//表情过滤器
InputFilter emojiFilter = new InputFilter() {

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
Pattern emoji = Pattern.compile(
"[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher emojiMatcher = emoji.matcher(source);
if (emojiMatcher.find()) {
return "";
}
return null;
}
};
//特殊字符过滤器
InputFilter specialCharFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String regexStr = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern pattern = Pattern.compile(regexStr);
Matcher matcher = pattern.matcher(source.toString());
if (matcher.matches()) {
return "";
} else {
return null;
}

}
};

et.setFilters(new InputFilter[]{emojiFilter});
}

/**
* 判断是否有表情符号
* @param string
* @return
*/
public boolean isEmoji(String string) {
@SuppressLint("WrongConstant")
Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(string);
return m.find();
}

public static boolean isEmoji(String string) {
Pattern p = Pattern.compile("/[\u1F60-\u1F64]|[\u2702-\u27B0]|[\u1F68-\u1F6C]|[\u1F30-\u1F70]|[\u2600-\u26ff]/g");
Matcher m = p.matcher(string);
return m.matches();
}