public class FilterActivity implements InputFilter {
Pattern pattern;
public FilterActivity(int beforeDecimal) {
pattern=Pattern.compile("([0-9]{0,"+(beforeDecimal-1)+"})?");
}
@Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int spanstart, int spanend) {
Matcher matcher=pattern.matcher(spanned);
if(!matcher.matches()){
return "";
}
return null;
}
}
当更改或编辑字段时它接受 a, 2a 我只需要接受 0-9
editText.setFilters(new InputFilter[]{new FilterActivity(3)});
我知道 android "number Decimal and number" 中的属性,但我尝试使用正则表达式来解决这个问题。
最佳答案
我同意@horcrux 的观点,但我认为由于你的乘数从 0 开始,你可以省略“?”:
"^([0-9]{0,"+(beforeDecimal-1)+"})$"
如果你不需要捕获结果,你甚至可以省略括号:
"^[0-9]{0,"+(beforeDecimal-1)+"}$"
但是您需要 anchor (^ 和 $)来指示匹配项的左侧或右侧可能没有任何内容。
@Raj 如果我正确理解你对@horcrux 的回答,那么你的数字后面有可选字母吗? 尝试:
"^([0-9]{0,"+(beforeDecimal-1)+"}[a-z]?)$"
或:
"^([0-9]{0,"+(beforeDecimal-1)+"}[a-zA-Z]?)$"
如果它们也可以是大写
关于java - 自定义输入过滤器接受正则表达式中的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858413/