views:

278

answers:

4

I have a string as follows;

dim str as string = "this       is    a string      .   "

I want to identify those multiple space chars and replace with one space char. using the replace function will replace all of them, so what is the correct way of doing such task?

A: 

Use a regular expression. as suggested by this other SO user here

Eoin Campbell
+2  A: 
import System.Text.RegularExpressions            

dim str as string  = "This is a      test   ."
dim r as RegEx = new Regex("[ ]+")
str = r.Replace(str, " ")
Tim Hoolihan
+2  A: 

Use the Regex class to match the pattern of "one or more spaces", and then replace all of those instances with a single space.

Here is the C# code to do it:

Regex regex = new Regex(" +");
string oldString = "this       is    a string      .   ";
string newString = regex.Replace(oldString, " ");
Andrew Garrison
+1  A: 

I'd use the \s+ modifier, which is easier to read

public Regex MyRegex = new Regex(
      "\\s+",
    RegexOptions.Multiline
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
    );


// This is the replacement string
public string MyRegexReplace =   " ";

string result = MyRegex.Replace(InputText,MyRegexReplace);

Or in VB

Public Dim MyRegex As Regex = New Regex( _
      "\s+", _
    RegexOptions.Multiline _
    Or RegexOptions.CultureInvariant _
    Or RegexOptions.Compiled _
    )


Public Dim MyRegexReplace As String =  " "


Dim result As String = MyRegex.Replace(InputText,MyRegexReplace)
Conrad