Created
April 27, 2016 13:05
-
-
Save twiceyuan/40837407e3a45bbd9b0e68bed75008cf to your computer and use it in GitHub Desktop.
根据正则表达式构造输入过滤器
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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