使用正则表达式测试EditText的内容

时间:2013-03-13 18:27:22

标签: android

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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) {

    }
  });