Article from : http://horribile.blogspot.com/2011/11/formatting-edittext-input-with-regular.html
It will be the short article. Now we will format text in EditText with regular expressions.
The simple class will extend Input Filter:
- public class PartialRegexInputFilter implements InputFilter {
- private Pattern mPattern;
- public PartialRegexInputFilter(String pattern){
- mPattern = Pattern.compile(pattern);
- }
- @Override
- public CharSequence filter(CharSequence source,
- int sourceStart, int sourceEnd,
- Spanned destination, int destinationStart,
- int destinationEnd)
- {
- String textToCheck = destination.subSequence(0, destinationStart).
- toString() + source.subSequence(sourceStart, sourceEnd) +
- destination.subSequence(
- destinationEnd, destination.length()).toString();
- Matcher matcher = mPattern.matcher(textToCheck);
- // Entered text does not match the pattern
- if(!matcher.matches()){
- // It does not match partially too
- if(!matcher.hitEnd()){
- return "";
- }
- }
- return null;
- }
- }
The trick is that if the input text does not match the pattern it can match it partially.
If so we will allow the text pasting.
And finally formatting a phone number:
- final String regex = "\\(\\d{3}\\)\\d{3}\\-\\d{2}\\-\\d{2}";
- txt.setFilters(
- new InputFilter[] {
- new PartialRegexInputFilter(regex)
- }
- );
- txt.addTextChangedListener(
- new TextWatcher(){
- @Override
- public void afterTextChanged(Editable s) {
- String value = s.toString();
- if(value.matches(regex))
- txt.setTextColor(Color.BLACK);
- else
- txt.setTextColor(Color.RED);
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start,
- int count, int after) {}
- @Override
- public void onTextChanged(CharSequence s, int start,
- int before, int count) {}
- }
- );
We have: