Skip to content

Instantly share code, notes, and snippets.

@twiceyuan
Created April 27, 2016 13:05
Show Gist options
  • Save twiceyuan/40837407e3a45bbd9b0e68bed75008cf to your computer and use it in GitHub Desktop.
Save twiceyuan/40837407e3a45bbd9b0e68bed75008cf to your computer and use it in GitHub Desktop.
根据正则表达式构造输入过滤器
import android.text.InputFilter;
import android.text.Spanned;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by twiceYuan on 11/10/15.
* <p>
* 根据正则表达式构造输入过滤器
*/
public class RegexInputFilter implements InputFilter {
Pattern mPattern;
public RegexInputFilter(String regex) {
mPattern = Pattern.compile(regex);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dStart, int dEnd) {
String result = dest.subSequence(0, dStart) + source.toString() + dest.subSequence(dEnd, dest.length());
Matcher matcher = mPattern.matcher(result);
if (!matcher.matches()) return dest.subSequence(dStart, dEnd);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment