Solved

Find next non-whitespace character in VB.Net string array

Posted on 2006-11-24
4
1,065 Views
Last Modified: 2012-05-05
In my VB.Net project I read in an entire text file and split the lines of the file into an array using split(FileContents, environment.newline())  

I now have to iterate through the lines array searching for keywords. Finding the keywords is easy (using IndexOf) but following each key word I need to read unknown strings that could be located on the same line as the keyword (separated from the keyword by spaces, tabs, etc) or on subsquent lines (possibly preceeded by tabs, spaces, etc.)

Here are some examples, all of which are legal syntax for my keyword/parameter sets:

  Keyword Parameter
  Keyword (tab) (tab) Parameter
  Keyword (space) (space) (space) Parameter
  Keyword (newline)
      (tab)(tab) Parameter

Since I never know what the parameter string is going to be, I can't use IndexOf() to find them. What I need to be able to do is find the next non-whitespace character following the keyword and then read characters until the next whitespace character and consider everything in-between to be the Parameter string.

So, what's the easiest way of doing this? I suspect there's a way to do it using regular expressions, but I have never used them before in .Net and I'm having a hard time finding examples online that do what I'm trying to do here.

Many, many thanks!
0
Comment
Question by:skwerm
  • 2
4 Comments
 
LVL 8

Expert Comment

by:YoungBonzi
ID: 18009293
       Dim s(10) As String
        Dim sKeyword As String
        Dim sParam As String

after you find the keyword

            'erase the spaces
            sParam = System.Text.RegularExpressions.Regex.Replace(s(i), " ", "")
            'erase the tabs
            sParam = System.Text.RegularExpressions.Regex.Replace(sParam, vbTab, "")
            'erase the keyword...leaving only the parameter and this point
            sParam = System.Text.RegularExpressions.Regex.Replace(sParam, sKeyword, "")

You can give this a run to see how you can apply it (it prints output to the Immediate Window. original array first, then the keywords and associated parameters):

        Dim s(10) As String
        Dim sKeyword(10) As String
        Dim sParam(10) As String

        Dim i As Integer

        'making a sample array that is filled with different keywords (asdf + a number),
        'parameters (a number), spaces and tabs
        For i = 0 To 10
            s(i) = "Keyword" + i.ToString + vbTab + "          " + i.ToString
        Next

        'print the array
        For i = 0 To 10
            Debug.WriteLine(s(i))
        Next

        'not to be taken literally, but to show you how you can use Regex to isolate a parameter

        i = s.GetUpperBound(0) 'size of array

        'goes through the array, putting keywords and parameters in arrays...you could do a 2D array
        'uncomment msgbox to see it actually isolating the parameter
        Do While (i >= 0)

            sKeyword(i) = "Keyword" + i.ToString 'sample keyword
            sParam(i) = System.Text.RegularExpressions.Regex.Replace(s(i), " ", "")
            ' MsgBox(sParam(i))
            sParam(i) = System.Text.RegularExpressions.Regex.Replace(sParam(i), vbTab, "")
            'MsgBox(sParam(i))
            sParam(i) = System.Text.RegularExpressions.Regex.Replace(sParam(i), sKeyword(i), "")
            'MsgBox(sParam(i))

            i = i - 1
        Loop

        'show the parameters in the Immediate window
        For i = 0 To 10
            Debug.WriteLine(sKeyword(i) & ": " & sParam(i))
        Next
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 18010552
Hi skwerm;

Here is a sample code to do what you want.

Imports System.IO

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        ' Read your file into a string variable
        Dim sr As New StreamReader("C:\Temp\KeywordParameter.txt")
        Dim input As String = sr.ReadToEnd()
        sr.Close()
        ' Get an array of paramters used with the keyword
        Dim Param() As String = FindParameters(input, "Keyword")

        ' The Param array will now hold the list of all the parameters using the keyword

    End Sub

    Private Function FindParameters(ByVal Input As String, _
        ByVal Keyword As String) As String()

        Dim Output() As String = Nothing

        If Input Is Nothing OrElse Input = String.Empty OrElse _
            Keyword Is Nothing OrElse Keyword = String.Empty Then
            MessageBox.Show("One or both parmeters is invalid")
            Return Output
        End If


        Keyword = Regex.Escape(Keyword) & "\s+([^\s]+)"
        ' If you are using VS .Net before version 2005 comment the above line out
        ' and uncomment the following statement.
        'Keyword = Regex.Replace(Keyword, "([\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\])", _
        '    "\$1") & "\s+([^\s]+)"
        Dim mc As MatchCollection = Regex.Matches(Input, _
            Keyword, RegexOptions.IgnoreCase Or RegexOptions.Multiline)

        If mc.Count > 0 Then
            Dim BuildOutput As String = String.Empty
            For Each m As Match In mc
                BuildOutput += m.Groups(1).Value & "|"
            Next
            BuildOutput = BuildOutput.Remove(BuildOutput.LastIndexOf("|"c))
            Output = BuildOutput.Split("|"c)
        End If

        Return Output

    End Function
End Class

Fernando
0
 

Author Comment

by:skwerm
ID: 18012127
Thank you both for your responses!

YoungBonzi's method looks like it may work, but FernandoSoto's seems more straight-forward and (possibly) more efficient. I'm going to spend some time picking apart the regular expression provided and see if I can get the gist of it.

Thanks, again -- Both of you!

0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 18012611
Not a problem, glad I was able to help. ;=)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now