简体   繁体   中英

different regex behaviour on different devices

I'm having a strange bug when I try to check an EditText (I want the text to be an IBAN, like FR76 2894 2894 2894 289 ), so I'm doing this (overriding my edit text's onTextChanged ):

// format with IBAN regex
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    editText.setText(editText.getText().toString().replaceAll(" ", "")
            .toUpperCase().replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ")); 
}

I'm doing a comparison with two different Android phones: an Asus Zenfone and an Honor 5C.

Both devices have the same bevahiour on first char typed (valid only if it's a letter). But then, when I type a second letter (text should be FR after this):

Honor 5C: (expected behaviour)

在此处输入图片说明

Asus Zenfone: (wrong behaviour)

在此处输入图片说明

Any idea? Thanks for your help.

As you can see in the documentation , it seems like a bad idea to call setText from onTextChanged :

This method is called when the text is changed, in case any subclasses would like to know. Within text, the lengthAfter characters beginning at start have just replaced old text that had length lengthBefore.

It is an error to attempt to make changes to text from this callback.

Have you tried using a TextWatcher , on your EditText ? For instance:

editText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        // This is only a sample code trying to reproduce your current behavior. 
        // I did not test it.
        String iban = s.toString().toUpperCase().replaceAll(" ", "");
        String compactIban = iban.replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ");
        s.replace(0, s.length(), compactIban);
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM