' CST1801 Visual Basic .NET ' Exercise 16.6 Number String solved using RegEx. ' Allen Benusa ' Apr 18, 2005 ' This imports must be added by hand Imports System.Text.RegularExpressions Public Class frmMain Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " #End Region Private Sub cmdCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCompute.Click Dim i As Integer Dim total As Integer = 0 Dim sNumString As String = txtNumString.Text Dim numMatch As String = "[0-9]{1,7}" Dim opMatch As String = "\+|-" Dim mcnum As MatchCollection = Regex.Matches(sNumString, numMatch) Dim mcop As MatchCollection = Regex.Matches(sNumString, opMatch) ' Number of number groups needs to be one more than operators to be valid. If mcnum.Count = mcop.Count + 1 Then total = Convert.ToInt32(mcnum(0).ToString()) For i = 1 To mcnum.Count - 1 Dim number As Integer = Convert.ToInt32(mcnum(i).ToString()) ' Apply the operator. If mcop(i - 1).ToString() = "+" Then total = total + number If mcop(i - 1).ToString() = "-" Then total = total - number Next lblResult.Text = Convert.ToString(total) Else lblResult.Text = "Invalid input" End If End Sub Private Sub txtNumString_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtNumString.Enter lblResult.Text = "" End Sub End Class