android 匹配限定的字元比如表情、中英文、符號
阿新 • • 發佈:2018-12-12
public class FilterUtil { //過濾表情正則表示式 public static final String EMOJI = "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]"; //匹配暱稱 public static final String MATCHER_NICKNAME = "[A-Za-z0-9_\\-\\u4e00-\\u9fa5]+"; //匹配數字、中英文、標點符號 public static final String MATCHER_DEFAULT = "[A-Za-z0-9_\\-\\u4e00-\\u9fa5\\p{P}]+"; //過濾金額 public static final String MATCHER_MONEY = "(^[1-9]\\d*(\\.\\d{1,2})?$)|(^[0]{1}(\\.\\d{1,2})?$)"; //匹配中文字元 public static final String MATCHER_CN = "[\\u4e00-\\u9fa5]"; /** * * @param context * @return 返回EditText輸入文字過濾器 */ public static InputFilter getInputFilter(final Context context,final String toast,final String regex){ InputFilter inputFilter = new InputFilter() { @Override public CharSequence filter(CharSequence charSequence, int start, int end, Spanned dest, int dstart, int dend) { if(charSequence.length()>0){ if(isMatcher(charSequence.toString(),regex)){ return null; }else{ Toast.makeText(context,toast,0).show(); return ""; } } return null; } }; return inputFilter; } /** * 正則表示式匹配 * @param content 待匹配內容 * @param regex 正則表示式 * @return true 匹配成功 */ public static boolean isMatcher(String content,String regex){ Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); return matcher.find(); } }