dart regex remove space phone

2,294

You may match and capture an optional +33 and then a digit followed with spaces or digits, and then check if Group 1 matched and then build the result accordingly.

Here is an example solution (tested):

var strs = ['aaaaaaaaa 06 12 34 56 78  aaaaaa', 'aaaaaaaa 0612345678 aaaaaa', 'aaaaaa +336 12 34 56 78 aaaaa', 'more +33 6 12 34 56 78'];
  for (int i = 0; i < strs.length; i++) {
    var rx = new RegExp(r"(?:^|\D)(\+33)?\s*(\d[\d ]*)(?!\d)");
    var match = rx.firstMatch(strs[i]);
    var result = "";
    if (match != null) {
      if (match.group(1) != null) {
        result = "0" + match.group(2).replaceAll(" ", "");
      } else {
        result = match.group(2).replaceAll(" ", "");
      }
      print(result);
  }
}

Returns 3 0612345678 strings in the output.

The pattern is

(?:^|\D)(\+33)?\s*(\d[\d ]*)(?!\d)

See its demo here.

  • (?:^|\D) - start of string or any char other than a digit
  • (\+33)? - Group 1 that captures +33 1 or 0 times
  • \s* - any 0+ whitespaces
  • (\d[\d ]*) - Group 2: a digit followed with spaces or/and digits
  • (?!\d) - no digit immediately to the right is allowed.

Spaces are removed from Group 2 with a match.group(2).replaceAll(" ", "") since one can't match discontinuous strings within one match operation.

Share:
2,294
Nitneuq
Author by

Nitneuq

Updated on December 05, 2022

Comments

  • Nitneuq
    Nitneuq 11 months

    I tried all this regex solution but no match REGEX Remove Space

    I work with dart and flutter and I tried to capture only digit of this type of string :

    case 1

         aaaaaaaaa 06 12 34 56 78  aaaaaa 
    

    case 2

        aaaaaaaa 0612345678 aaaaaa 
    

    case 3

       aaaaaa +336 12 34 56 78 aaaaa
    

    I search to have only 0612345678 with no space and no +33. Just 10 digit in se case of +33 I need to replace +33 by 0

    currently I have this code \D*(\d+)\D*? who run with the case 2

    • Wiktor Stribiżew
      Wiktor Stribiżew over 5 years
      Why did you choose to try \D*(\d+)\D*?? It does not match digits separated with spaces. What is the rule for the pattern? The first digit/space chunk in the string?
    • Nitneuq
      Nitneuq over 5 years
      sorry (\d+) is sufficient currently it match with aaaaaaaa 0612345678 aaaaaa the result is 0612345678. but this code no working if there is space between digit like 06 12 34 56 78
  • Nitneuq
    Nitneuq over 5 years
    sorry I have an other case ... with +33 6 12 34 56 78 it return 33612345678
  • Nitneuq
    Nitneuq over 5 years
    it's ok with (r"(?:^|\D)(\+33)?\s?(\d[\d ]*)(?!\d)")
  • Wiktor Stribiżew
    Wiktor Stribiżew over 5 years
    @QuentinGuichot Right, you may also use \s* to match 0 or more whitespaces, rather than \s? that matches 1 or 0 whitespaces. I updated the answer to account for that scenario as well.