twiceyuan
4/27/2016 - 1:05 PM

根据正则表达式构造输入过滤器

根据正则表达式构造输入过滤器


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;
    }
}