EditText中只允许输入数字、字母、汉字和-
- /**
- * 匹配正则表达式
- * @param str
- * @return
- * @throws PatternSyntaxException
- */
- public static String stringFilter(String str)throws PatternSyntaxException {
- // 只允许字母、数字和汉字-
- //String regEx = "[^a-zA-Z0-9-u4E00-u9FA5]";
- String regEx = "[^a-zA-Z0-9\-u4E00-u9FA5]";
- Pattern p = Pattern.compile(regEx);
- Matcher m = p.matcher(str);
- return m.replaceAll("").trim();
- }
复制代码
- //给EditText添加TextWatcher监听,下面方法中进行判断.
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- String editable = mHouseNumEt.getText().toString();
- String str = stringFilter(editable.toString());
- if(!editable.equals(str)){
- mHouseNumEt.setText(str);
- //设置新的光标所在位置
- mHouseNumEt.setSelection(str.length());
- }
- }
复制代码 |