Reputation: 13742
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?
Upvotes: 0
Views: 1124
Reputation: 8389
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)
Upvotes: 1
Reputation: 7027
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, " ");
Upvotes: 2
Reputation: 12396
import System.Text.RegularExpressions
dim str as string = "This is a test ."
dim r as RegEx = new Regex("[ ]+")
str = r.Replace(str, " ")
Upvotes: 2
Reputation: 44308
Use a regular expression. as suggested by this other SO user here
Upvotes: 0