KnowDotNet Visual Organizer

Parsing with Regular Expressions - Counting Leading Spaces in a String

CountSpacesBeforeFirstChar

by Les Smith and Brian Davis
Print this Article Discuss in Forums

Is there a function to count the number of leading spaces in a line of text?  This is a valuable function when parsing and indenting source code.  There is not built in function in VB6 or .NET to do this, but the following functions show the VB6 and .NET solution to the problem.  In writing add-ins, I do a lot of parsing of source code.  I needed a function that would tell me how many spaces there are at the start of a line of text before the first non blank character.  In VB6, I wrote the following function to loop through the leading characters and count the spaces.

   Public Overloads Function CountSpacesBeforeFirstChar(ByVal psIN As String) _
      
As Integer
      ' Count the number of spaces before first
      ' non space character in a source line
      Dim iSpCnt As Integer

      For iSpCnt = 0 To Len(psIN) - 1
        
If Mid$(psIN, iSpCnt + 1, 1) <> " " Then
            CountSpacesBeforeFirstChar = iSpCnt
            
Exit Function
         End If
      Next iSpCnt
      CountSpacesBeforeFirstChar = iSpCnt

  
End Function

In .NET, using Regular Expressions is much simpler and potentially faster.

   Public Overloads Function CountSpacesBeforeFirstChar(ByVal Source As String) _
                                                        
As Integer
      ' Count the number of spaces before first
      ' non space character in a source line
      Return CountSpacesBeforeFirstChar(Source, 0)
  
End Function
   Public Overloads Function CountSpacesBeforeFirstChar(ByVal Source As String, _
                                                        
ByVal StartAt As Integer) _
                                                        
As Integer
      ' Count the number of spaces before first
      ' non space character in a source line,
      ' beginning at piST
      ' since the regex match includes the first non-black char,
      ' sub 1 from match.length
      Return Regex.Match(Source.Substring(StartAt), "^ *[^ ]").Length - 1
  
End Function

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing