Regular Expression Questions

kpao

Active member
Joined
Apr 3, 2006
Messages
29
Programming Experience
Beginner
Suppose I have a string like that:

VB.NET:
Dim s As String = "a   b c   d  e         f   g    h"

how can i use the regular expression to capture the space characters and return the following result?

result: s = "a b c d e f g h"
 
Last edited by a moderator:
You can use Regex.Replace to replace multiple spaces with one.
VB.NET:
s= Regex.Replace(s, " {2,}", " ")
 
Here is another way (copied from microsoft help):

VB.NET:
Imports System.Text.RegularExpressions

Module Module1
    Public Sub Main()
        ' Create a regular expression that matches a series of one 
        ' or more white spaces.
        Dim pattern As String = "\s+"
        Dim rgx As New Regex(pattern)

        ' Declare a string consisting of text and white spaces.
        Dim s As String = "a   b c   d  e         f   g    h"

        ' Replace runs of white space in the input string with a
        ' comma and a blank.
        Dim outputStr As String = rgx.Replace(s, " ")

        ' Display the resulting string.
        Console.WriteLine("Pattern:       ""{0}""", pattern)
        Console.WriteLine("Input string:  ""{0}""", s)
        Console.WriteLine("Output string: ""{0}""", outputStr)
    End Sub 'Main

End Module
 
Back
Top