【问题标题】:different regex behaviour on different devices不同设备上的不同正则表达式行为
【发布时间】:2017-12-08 14:36:55
【问题描述】:

当我尝试检查 EditText 时遇到一个奇怪的错误(我希望文本是 IBAN,例如 FR76 2894 2894 2894 289),所以我正在这样做(覆盖我的编辑文本 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 ")); 
}

我正在与两款不同的 Android 手机进行比较:华硕 Zenfone 和荣耀 5C。

两个设备在输入第一个字符时具有相同的行为(仅当它是一个字母时才有效)。但是,当我输入第二个字母时(文本应该是 FR 之后):

荣誉 5C:(预期行为)

华硕 Zenfone:(错误行为)

有什么想法吗? 感谢您的帮助。

【问题讨论】:

  • 手机的操作系统有哪些(ROM和版本)?
  • 嗨 @Antoine,荣耀 5C:Android 7.0/NEM-L51 和华硕 Zenfone:5.0.1/Z00D。会不会是华硕的版本太旧了?
  • Android 手机行为可能会根据版本和制造商覆盖而改变。所以 Zenfone 版本可能是你麻烦的原因,但不一定是因为它太旧了。

标签: android regex asus


【解决方案1】:

正如您在the documentation 中看到的那样,从onTextChanged 调用setText 似乎是个坏主意:

当文本改变时调用这个方法,以防任何子类 想知道。在文本内,lengthAfter 个字符开始 在开始时刚刚替换了长度为 lengthBefore 的旧文本。

尝试从此回调中更改文本是错误的。

您是否尝试过在您的EditText 上使用TextWatcher?例如:

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);
      }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多