【问题标题】:How to split a string on range如何在范围内拆分字符串
【发布时间】:2020-06-04 09:59:20
【问题描述】:

我是 Flutter 的新手,我需要你的帮助。 谁能帮助我如何将这段代码行从 JavaScript 写到 Flutter:

onInputChange(event, backspace) {
let newVal = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
  newVal = newVal.substring(0, newVal.length - 1);
}
if (newVal.length === 0) {
  newVal = '';
} else if (newVal.length <= 3) {
  newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
  newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2'); 
} else if (newVal.length <= 10) {
  newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
} else {
  newVal = newVal.substring(0, 10);
  newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
}
this.ngControl.valueAccessor.writeValue(newVal);

}

我在 .splitMapJoin 中看到了一些东西,但我做不到。

【问题讨论】:

    标签: regex flutter dart substring


    【解决方案1】:

    试试replaceFirstMapped

    var value = '1234567890';
    var regExp = RegExp(r'^(\d{0,3})(\d{0,3})(\d{0,4})');
    var phoneNumber = value.replaceFirstMapped(regExp, (match) {
      return '(${match.group(1)}) ${match.group(2)}-${match.group(3)}';
    });
    
    print(phoneNumber); //(123) 456-7890
    

    问题编辑后更新

    你需要这样的东西吗:

    format(String value) {
      var regExp2 = RegExp(r'^(\d{0,3})(\d{0,3})(\d{0,4})');
      return value.replaceFirstMapped(regExp2, (match) {
        var res = '';
        if (match.group(1).isNotEmpty) {
          res += '(${match.group(1)})';
        }
        if (match.group(2).isNotEmpty) {
          res += ' ${match.group(2)}';
        }
    
        if (match.group(3).isNotEmpty) {
          res += '-${match.group(3)}';
        }
    
        return res;
      });
    }
    
    var value = '1234567890';
    var value2 = '12345';
    
    print(format(value)); //(123) 456-7890
    print(format(value2)); //(123) 45 
    

    【讨论】:

    • 我想在 onChange 函数上使用它,它不起作用。我已经编辑了我的问题,你能看看吗
    • 看 Kherel,我为我在 TextField 上写的每个键调用这个函数,我得到的是“(5)(4)(3)(2)(1)”。这不是我想要的
    • 这很难说,但可能你没有正确使用 TextEditingController。因为你会更容易使用pub.dev/packages/mask_text_input_formatter包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    相关资源
    最近更新 更多