Search code examples
regexflutterregexp-replace

How to replace multiple patterns with RegExp


I have phone numbers like +41 000 0000 000 and currently I only can keep + sign with my code but I also need to remove spaces from this numbers.

Here is my current function

String flattenPhoneNumber(String phoneStr) {
    return phoneStr.replaceAllMapped(RegExp(r'^(\+)|D'), (Match m) {
      return m[0] == "+" ? "+" : "";
    });
}

How can I remove spaces as well as keeping my + signs?


Solution

  • Solved

    I've changed my code to following and its working as it supposed to:

    String flattenPhoneNumber(String phoneStr) {
        return phoneStr.replaceAll(' ', '').replaceAllMapped(RegExp(r'^(\+)|D'), (Match m) {
          return m[0] == "+" ? "+" : "";
        });
    }