使用dart将字符串格式设置为电话号码(123)456-6789模式

ufj5ltwl  于 2023-11-14  发布在  其他
关注(0)|答案(6)|浏览(75)

这是我的代码

void main() {

  String phoneNumber = '123456789';

  String formattedPhoneNumber = phoneNumber.replaceFirst("(\d{3})(\d{3})(\d+)", "(\$1) \$2-\$3");

  print('Formatted number ${formattedPhoneNumber}');

}

字符串

输出:

编号123456789
我想输出为已确认的号码(123)456-6789

ut6juiuv

ut6juiuv1#

试试这个

print('1234567890'.replaceAllMapped(RegExp(r'(\d{3})(\d{3})(\d+)'), (Match m) => "(${m[1]}) ${m[2]}-${m[3]}"));

字符串

cld4siwp

cld4siwp2#

创建自定义Masked类

import 'package:flutter/material.dart';

class MaskedTextController extends TextEditingController {
  MaskedTextController({String text, this.mask, Map<String, RegExp> translator})
      : super(text: text) {
    this.translator = translator ?? MaskedTextController.getDefaultTranslator();

    this.addListener(() {
      var previous = this._lastUpdatedText;
      if (this.beforeChange(previous, this.text)) {
        this.updateText(this.text);
        this.afterChange(previous, this.text);
      } else {
        this.updateText(this._lastUpdatedText);
      }
    });

    this.updateText(this.text);
  }

  String mask;

  Map<String, RegExp> translator;

  Function afterChange = (String previous, String next) {};
  Function beforeChange = (String previous, String next) {
    return true;
  };

  String _lastUpdatedText = '';

  void updateText(String text) {
    if(text != null){
      this.text = this._applyMask(this.mask, text);
    }
    else {
      this.text = '';
    }

    this._lastUpdatedText = this.text;
  }

  void updateMask(String mask, {bool moveCursorToEnd = true}) {
    this.mask = mask;
    this.updateText(this.text);

    if (moveCursorToEnd) {
      this.moveCursorToEnd();
    }
  }

  void moveCursorToEnd() {
    var text = this._lastUpdatedText;
    this.selection = new TextSelection.fromPosition(
        new TextPosition(offset: (text ?? '').length));
  }

  @override
  void set text(String newText) {
    if (super.text != newText) {
      super.text = newText;
      this.moveCursorToEnd();
    }
  }

  static Map<String, RegExp> getDefaultTranslator() {
    return {
      'A': new RegExp(r'[A-Za-z]'),
      '0': new RegExp(r'[0-9]'),
      '@': new RegExp(r'[A-Za-z0-9]'),
      '*': new RegExp(r'.*')
    };
  }

  String _applyMask(String mask, String value) {
    String result = '';

    var maskCharIndex = 0;
    var valueCharIndex = 0;

    while (true) {
      // if mask is ended, break.
      if (maskCharIndex == mask.length) {
        break;
      }

      // if value is ended, break.
      if (valueCharIndex == value.length) {
        break;
      }

      var maskChar = mask[maskCharIndex];
      var valueChar = value[valueCharIndex];

      // value equals mask, just set
      if (maskChar == valueChar) {
        result += maskChar;
        valueCharIndex += 1;
        maskCharIndex += 1;
        continue;
      }

      // apply translator if match
      if (this.translator.containsKey(maskChar)) {
        if (this.translator[maskChar].hasMatch(valueChar)) {
          result += valueChar;
          maskCharIndex += 1;
        }

        valueCharIndex += 1;
        continue;
      }

      // not masked value, fixed char on mask
      result += maskChar;
      maskCharIndex += 1;
      continue;
    }

    return result;
  }
}

字符串

现在在主dart文件中调用它

var maskedController = MaskedTextController(mask: '(000) 000-0000');

TextField(
  controller: maskedController,
  style: Styles.textNormalStyle,
  maxLines: 1,
),

kgsdhlau

kgsdhlau3#

此解决方案适用于您的此特定问题和场景。
你可以用下面的代码来实现。

String formattedPhoneNumber = "(" + phoneNumber.substring(0,3) + ") " + 
phoneNumber.substring(3,6) + "-" +phoneNumber.substring(6,phoneNumber.length);

字符串

kpbwa7wx

kpbwa7wx4#

Ricardo指出了一个很棒的库,但他的答案只对了一半。除了intl_phone_number_input,你还需要安装libphonenumber_plugin

intl_phone_number_input: ^0.7.0+2
libphonenumber_plugin:

字符串
方法getRegionInfoFromPhoneNumber“发现”号码来自哪个国家,例如+55.它会解释为来自巴西,并相应地格式化电话号码。您也可以通过将国家的首字母缩略词传递到方法中来明确地告诉电话号码来自哪里,例如await PhoneNumber.getRegionInfoFromPhoneNumber(phone, "US");如果国家代码与您输入的号码不匹配,它将忽略该代码。

String phone = "+19795555555";
PhoneNumber number =
  await PhoneNumber.getRegionInfoFromPhoneNumber(phone);
String formattedNumber = await PhoneNumberUtil.formatAsYouType(
number.phoneNumber!,
number.isoCode!,
);
print(formattedNumber); // -> prints: '+1 979-555-5555'

baubqpgj

baubqpgj5#

您也可以使用:用途:https://pub.dev/packages/intl_phone_number_input/example

String phoneNumber =  '+234 500 500 5005';
PhoneNumber number = await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber);
String parsableNumber = number.parseNumber();
`controller reference`.text = parsableNumber

字符串

6tr1vspr

6tr1vspr6#

最好使用扩展:

extension StringExtension on String {
  String phoneFormat() => replaceAllMapped(
        RegExp(r'(\d{2})(\d{3})(\d{3})(\d+)'),
        (final Match m) => '${m[1]} (${m[2]}) ${m[3]}-${m[4]}',
      );
}

字符串

相关问题