0

请我希望 EditText 由两个字母和五个数字组成。我想使用正则表达式。但我不明白如何使用它。先感谢您

4

2 回答 2

0
boolean validate(String str){
    int letters = 0;
    int numbers = 0;
    int others = 0;
    for(int i=0; i<str.length(); i++){
        char ch = str.getAt(i);
        if(Character.isLetter(ch)){
            letters++;
        }
        else if (Character.isDigit(ch)){
            numbers++;
        }
        else{
            others++;
        }
    }
    return others == 0 && numbers==5 && letters == 2;
}
于 2013-03-13T18:40:06.250 回答
0
EditText edit = (EditText) this.findViewById(R.id.edit_text);


  edit.addTextChangedListener(new TextWatcher() {            
    @Override
    public void onTextChanged(CharSequence s, int start, 
                              int before, int count) {
    char[] c_arr = s.toCharArray();
    int letterCount=0;
    int digitCount=0;

        for(Character c : c_arr){

            try{
                Integer.parseInt(c.toString())
                digitCount++;
                if(digitCount > 2){
                    // alert here
                    s = s.substring(0, s.length() - 1);
                    EditText edit = (EditText) this.findViewById(R.id.edit_text);
                    edit.setText(s);
                    break;
                }
            }catch (NumberFormatException e) {
                letterCount++;
                if(letterCount > 5){
                    // alert here
                    s = s.substring(0, s.length() - 1);
                    EditText edit = (EditText) this.findViewById(R.id.edit_text);
                    edit.setText(s);
                    break;
                }
            }
        }    
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after) {}

    @Override
    public void afterTextChanged(Editable s) {

    }
  });
于 2013-03-13T18:46:35.370 回答