Solved

How do I return the next Alpha Character when a specific text string is found?

Posted on 2016-11-30
4
19 Views
Last Modified: 2016-12-01
I have about 20-30k .nc files (text files with ".nc" suffix) which are machine code for our CNC turning centers.

Here is a sample of a .nc file

% 
:4082(C-408-2MA-REV. D-OP10 BND 51S2 1.812" 12L14 05/22/08)

Open in new window


And another Sample:

%
O1(CNB-48-2S)
$1
(CNB-48-2S-REV.K)

Open in new window


 I have a Windows form application written in Visual Basic.Net that our operators use to search by part number to find all existing .nc files for whatever part number they are searching for. This found data is then is stored in a datatable which in turn populates a datgridview.

Here is a screenshot of the app with a search and found data:

Application Screen Shot

I need to read the 1st few lines of each .nc file find the string "Rev" and then return the next Alpha character following the "Rev" String. Not all .nc files are structured the same. Some have special characters after the "Rev: String some do not.

The sample above has a period, space, then the Alpha Character "D". following the "Rev" String. I need to know how to find and then add the "D" string to the data table so it will be shown in the datagridview on each search.

I'm not very hip on String manipulation any help would be greatly appreciated.

Here is the Code for the Windows Form:

Imports System.IO

Public Class frmCNCPro
    Private Sub CNCPro_Load(sender As Object, e As EventArgs) Handles Me.Load
        Show()
        Me.DoubleBuffered = True
        txtBrowseCNC.Text = GVar.CNCdDir
        txtSearchCNC.Text = frmCPS.txtPartNum.Text
        txtSearchCNC.Focus()
    End Sub
    Private Function Builder() As DataTable
        '############################################################################################
        '# This function starts by searching thru the CNC programs Directory and finds .NC or PPF   #
        '# files depending on the selection from the two radio buttons. Once the data is is parsed  #
        '# it Is stored in a datatable!                                                                                                               #
        GVar.CNCsDir = txtBrowseCNC.Text
        Dim _dtNC As DataTable = New DataTable("FoundNCFiles")
        _dtNC.Columns.Add("FullName")
        _dtNC.Columns.Add("FileName")
        _dtNC.Columns.Add("Folder")
        _dtNC.Columns.Add("CreationTime", GetType(Date))
        _dtNC.Columns.Add("LastWriteTime", GetType(Date))

        Dim ext_nc As String = ".NC"
        'Loop thru each file in the directory and subdirectories                                                    
        Dim di As New DirectoryInfo(GVar.CNCsDir)
        Dim ex_nc As String = "*.NC"
        Dim ex_ppf As String = "*.ppf"
        Dim extUsed As String = ""
        If rbNC_files.Checked = True Then extUsed = ex_nc
        If rbPPF_files.Checked = True Then extUsed = ex_ppf
        For Each ncFile As FileInfo In di.GetFiles(extUsed, SearchOption.AllDirectories)
            Dim _drNC As DataRow = _dtNC.NewRow
            Dim foStr = Path.GetDirectoryName(ncFile.FullName)
            Dim split = foStr.Split("\").LastOrDefault
            _drNC("FullName") = ncFile.FullName
            _drNC("FileName") = ncFile.Name
            _drNC("Folder") = split
            _drNC("CreationTime") = ncFile.CreationTime
            _drNC("LastWriteTime") = ncFile.LastWriteTime
            'add the new row
            _dtNC.Rows.Add(_drNC)
        Next
        Return _dtNC
        '#                                                                                         #
        '###########################################################################################
    End Function

    Public Sub DisplayBuilderData()
        '############################################################################################
        '# This Subroutine uses the data from the Builder() Function and populates a datagridview!  #

        Dim dTableNC As New DataTable
        Dim bsNC As New BindingSource

        dTableNC = Builder()
        bsNC.DataSource = dTableNC
        dgvCNC.DataSource = bsNC
        dgvCNC.Columns(0).Visible = False
        dgvCNC.Columns(1).Width = 250
        dgvCNC.Columns(2).Width = 182
        dgvCNC.Columns(3).Width = 182
        dgvCNC.Columns(4).Width = 182

        bsNC.Filter = String.Format("[FileName] Like '{0}%'", txtSearchCNC.Text)
        '#                                                                                         #
        '###########################################################################################
    End Sub
    Private Sub btnBrowseCNC_Click(sender As Object, e As EventArgs) Handles btnBrowseCNC.Click
        If (fbdCNC.ShowDialog() = DialogResult.OK) Then
            txtBrowseCNC.Text = fbdCNC.SelectedPath
        End If
    End Sub

    Private Sub frmCNCPro_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        WindowState = FormWindowState.Minimized
        Hide()
        Visible = False
        e.Cancel = True
    End Sub

    Private Sub txtSearchCNC_TextChanged(sender As Object, e As EventArgs) Handles txtSearchCNC.TextChanged, rbNC_files.Click, rbPPF_files.Click
        Timer1.Interval = 1000 'ms
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        DisplayBuilderData()
    End Sub

    Private Sub dgvCNC_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvCNC.CellContentDoubleClick
        If e.ColumnIndex = 1 Then
            Process.Start(dgvCNC.Rows(e.RowIndex).Cells(0).Value.ToString())
        End If
    End Sub

    Private Sub btnCountNC_Click(sender As Object, e As EventArgs) Handles btnCountNC.Click
        ''This Sub-Routine displays the total number of dwf files in the Carter Prints folder on our server.
        Dim dirInfo As New System.IO.DirectoryInfo(GVar.CNCdDir)
        Dim i_NC As Integer
        Dim i_ppf As Integer
        i_NC = dirInfo.GetFiles("*.NC", SearchOption.AllDirectories).Count
        i_ppf = dirInfo.GetFiles("*.ppf", SearchOption.AllDirectories).Count
        MessageBox.Show("Total number of .NC files is " & i_NC & "! And total number of .ppf files is " & i_ppf & "!", "File Count Dialog")
    End Sub
End Class

Open in new window

0
Comment
Question by:Steve Williams
  • 2
4 Comments
 
LVL 12

Accepted Solution

by:
Jeff Darling earned 350 total points
Comment Utility
Regex might be useful for this problem.

 
        Dim text1 As String = ":4082(C-408-2MA-REV. D-OP10 BND 51S2 1.812"" 12L14 05/22/08)"
        Dim text2 As String = "(CNB-48-2S-REV.K)"
        Dim text3 As String = "No r e v on this string"


        Console.WriteLine(parseREV(text1)) ' returns D
        Console.WriteLine(parseREV(text2)) ' returns K
        Console.WriteLine(parseREV(text3)) ' returns Not Found

Open in new window


Public Function parseREV(inputdata)
        Dim pattern As String = ".*REV\.(.*)"
        Dim result

        ' Instantiate the regular expression object.
        Dim r As Regex = New Regex(pattern, RegexOptions.IgnoreCase)

        ' Match the regular expression pattern against a text string.
        Dim m As Match = r.Match(inputdata)
        Dim g As Group = m.Groups(1)

        If m.Length > 0 Then
            result = g.ToString().Trim.Substring(0, 1)
        Else
            result = "Not Found"
        End If

        Return result

    End Function

Open in new window

0
 
LVL 32

Assisted Solution

by:sarabande
sarabande earned 150 total points
Comment Utility
a simple "find" should do it as well

dim strNextAlpha as String
dim Result

Result = strInputLine.IndexOf("-REV.")

If Result > 0 then
    strNextAlpha = strInputLine.Substring(Result+5).Trim().Substring(0, 1)
End If

Open in new window

   

Sara
0
 
LVL 1

Assisted Solution

by:Steve Williams
Steve Williams earned 0 total points
Comment Utility
@Jeff Darling & @Sarabande:

After spending the day manipulating the code from Jeff and saras code I have a working application. The following is the result.

The Screenshot:

Screenshot of working application!
The Code:
 
 Public Function parseREV(inputdata) As String

        Dim revisionP As String = "revision[^A-Z]*([A-Z]{1})"
        Dim revP As String = "rev[^A-Z]*([A-Z]{1})"

        ' Instantiate the regular expression object.
        Dim revisionR As Regex = New Regex(revisionP, RegexOptions.IgnoreCase)
        Dim revR As Regex = New Regex(revP, RegexOptions.IgnoreCase)

        ' Match the regular expression pattern against a text string.
        Dim m As Match

        m = revisionR.Match(inputdata)

        If Not m.Success Then m = revR.Match(inputdata)

        If Not m.Success Then Return ""

        Return m.Groups(1).ToString()

    End Function

 Private Function Builder() As DataTable
        '############################################################################################
        '# This function starts by searching thru the CNC programs Directory and finds .NC or PPF   #
        '# files depending on the selection from the two radio buttons. Once the data is is parsed  #
        '# it Is stored in a dtatable and then returned as a datatable!                             #
        GVar.CNCsDir = txtBrowseCNC.Text
        Dim _dtNC As DataTable = New DataTable("FoundNCFiles")
        _dtNC.Columns.Add("FullName")
        _dtNC.Columns.Add("FileName")
        _dtNC.Columns.Add("Folder")
        _dtNC.Columns.Add("CreationTime", GetType(Date))
        _dtNC.Columns.Add("LastWriteTime", GetType(Date))
        _dtNC.Columns.Add("Rev")

        Dim ext_nc As String = ".NC"
        'Loop thru each file in the directory and subdirectories                                                    
        Dim di As New DirectoryInfo(GVar.CNCsDir)
        Dim ex_nc As String = "*.NC"
        Dim ex_ppf As String = "*.ppf"
        Dim extUsed As String = ""
        If rbNC_files.Checked = True Then extUsed = txtSearchCNC.Text + ex_nc
        If rbPPF_files.Checked = True Then extUsed = txtSearchCNC.Text + ex_ppf
        For Each ncFile As FileInfo In di.GetFiles(extUsed, SearchOption.AllDirectories)
            Dim _drNC As DataRow = _dtNC.NewRow
            Dim foStr = Path.GetDirectoryName(ncFile.FullName)
            Dim split = foStr.Split("\").LastOrDefault
            _drNC("FullName") = ncFile.FullName
            _drNC("FileName") = ncFile.Name
            _drNC("Folder") = split
            _drNC("CreationTime") = ncFile.CreationTime
            _drNC("LastWriteTime") = ncFile.LastWriteTime

            Dim rev As String = ""

            For Each line As String In System.IO.File.ReadAllLines(ncFile.FullName)
                If rev = "" Then
                    rev = parseREV(line)
                End If
            Next
            _drNC("Rev") = rev
            'add the new row
            _dtNC.Rows.Add(_drNC)
        Next
        Return _dtNC
        '#                                                                                         #
        '###########################################################################################
    End Function

Open in new window


I realized after I created this post that the ".nc" files called out the revision two different ways.  With "Rev" and "Revision". Also there are files that have no revision so I had to account for that as well. I really appreciate your efforts in helping me with this. I'm going to award the majority of points to Jeff, because I chose his solution over sara's this was due to him using RegEx which has more options.

My initial coding experianced major lag times. This happened because I was reading every file in the directory which took forever. I changed the code to only read the files that was found in my filter on the textbox. This made all the difference in the world in the response time.

Thank you both for your valuable time.
0
 
LVL 1

Author Closing Comment

by:Steve Williams
Comment Utility
Both of your solutions helped me get to a correct solution. This gave me a good base to start from and eventually worked into a functional application.

Much appreciation to both.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
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 …
This video discusses moving either the default database or any database to a new volume.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

744 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

16 Experts available now in Live!

Get 1:1 Help Now