0

The input string having multiple whitespaces, and the result should have only one white space left, other whitespaces must be replaced with string.Empty

Input String: +1 580 5691 234 or (435) 772-5992

Output String: +1 5805691234 or +1 4357725992

Regex.Replace(text, @"[^\d]", string.Empty) replaces all the whitespaces.

Felix D.
  • 4,811
  • 8
  • 38
  • 72
CodeConstruct
  • 290
  • 3
  • 17

3 Answers3

0

You don't have to do it all within one line:

Remove the special characters as you like, get the position of the first space, remove spaces with your regex only in the substring after the first space.

Matheus Lacerda
  • 5,983
  • 11
  • 29
  • 45
0

If you absolutely must do it with a single regex, this might be a solution for you:

Replace

^(?:\+1)?\D*(\d*)?\D*(\d*)?\D*(\d*)?\D*(\d*)?\D*(\d*)?$

with

+1 $1$2$3$4$5

Using 5 separate capture groups, it captures only digits, possibly separated by non-digits. If there are less than 5 digit groups, they're simply ignored.

Note that the optional preceding country code isn't captured either, and that the replace string always inserts it (back, if it existed).

This specific example limits the number of digit groups to 5, but could easily be expanded.

Here at regexstorm.net.

and illustrated here at regex101.

SamWhan
  • 8,296
  • 1
  • 18
  • 45
0

The .NET Regex engine can manage this with a lookbehind:

(?<=\s+.*)\s+

It matches all blocks of whitespace which are preceded by at least one block of whitespace followed by some non-whitespace characters.

Using it as Regex.Replace(text, "(?<=\s+.*)\s+", string.Empty) on the string +1 580 5691 234 produces the output +1 5805691234.

Paul Turner
  • 38,949
  • 15
  • 102
  • 166