Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Windows Development  »  Creating a regular expression checker
Creating a regular expression checker
by Curtis Mitchell | Published  03/08/2002 | Windows Development | Rating:
Curtis Mitchell

Curtis Mitchell is the managing director of Vesource Corporation. He also serves as the VP of Operations for Foul Mouth Entertainment, LLC.

He has been a professional developer for the past four years focusing primarily on Microsoft products and technologies. He is very proficient in Visual Basic, ASP, SQL Server, and Oracle. However, he remains committed to life-long learning and personal development.

 

View all articles by Curtis Mitchell...
Creating a regular expression checker

This article will attempt to explain the steps involved with creating a WinForm application that will validate regular expressions using the System.Text.RegularExpression namespace. The application will accept two inputs. The first input will be a string to search. The second input will be the regular expression that serves as our search criteria.

Let me take the time to say I seen an application written by another developer that served the same purpose as this application. Unfortunately, I do not remember that person's name, but he or she deserves credit for the idea behind this application. I wrote the code for this application because I thought it would be a good application to learn with.

This article is written primarily for beginners. It assumes the reader has a fundamental knowledge of regular expressions, Visual Studio.NET, and VB.NET.

Let's begin!

Step 1 Create the project
Open Visual Studio.NET and create a Visual Basic windows application project called "RegXP".

Step 2 Configure the form
Using the property explorer in the IDE set the properties of the form as follows:

PropertyValue
FormBorderStyleFixedToolWindow
NamefrmMain
TextRegular Expressions Checker
TopMostTrue
Size408, 402

NOTE: Right-click on the RegXP project. Select properties, and change the start-up object from form1 to frmMain.

NOTE: Some properties have been provided for aesthetic purposes, but they can be set at your discretion.

Step 3 Add Controls to form
The following controls will be added to frmMain:

Control NameType
txtSearchStringTextbox
txtRegExpTextbox
lblSSLabel
lblRELabel
gbOptionsGroupBox
cbIgnoreCaseCheckbox
cbRightToLeftCheckbox
btnTestButton
btnMatchButton
btnCancelButton
lvResultsListview

The properties for the aforementioned controls are configured as follows:

txtSearchString

PropertyValue
Location64, 16
NametxtSearchString
Size328, 20
TabIndex0
Text""
BorderStyleFixedSingle

txtRegExp

PropertyValue
Location64, 48
NametxtRegExp
Size328, 20
TabIndex1
Text""
BorderStyleFixedSingle

This control needs a little validation to ensure the regular expressions are not JavaScript style regular expressions. Add the following code to a procedure that handles the leave event of txtRegExp:

'check to see if the user attempted to add the forward slashes to the regular 
' expression
If txtRegExp.Text.StartsWith("/"= True And txtRegExp.Text.EndsWith_
    "/"= True Then
    'Remove the slash at the end of the string
    txtRegExp.Text = txtRegExp.Text.Remove(txtRegExp.Text.Length - 11)
    'Remove the slash at the beginning of the string
    txtRegExp.Text = txtRegExp.Text.Remove(01)
End If
Generated using PrettyCode.Encoder

lblSS

PropertyValue
NamelblSS
Text"String:"
TabIndex3
Size37, 13
Location8, 16

lblRE

PropertyValue
NamelblRE
Text"Reg Exp:"
TabIndex4
Size51, 13
Location8, 48
AutosizeTrue

lvResults

PropertyValue
MultiselectFalse
Size376, 144
Location8, 152

We need to add some initialization code for lvResults in the constructor of the form. Add the following code after the call to InitializeComponent() in the New() procedure of the form:

'Add columns to the listview control
LvResults.Columns.Add("Position"-2HorizontalAlignment.Left)
LvResults.Columns.Add("Value"-2HorizontalAlignment.Left)
LvResults.FullRowSelect = True
LvResults.GridLines = True
LvResults.View = View.Details
Generated using PrettyCode.Encoder

gbOptions

PropertyValue
Text"Options"
Size328, 48
Location64, 80

Note: The following controls need to be added to gbOptions. This can be accomplished by selecting gbOptions, then single clicking on the control you would like to add in the toolbox. Lastly, single click within the pre-selected gbOptions and VS.NET will automatically add the control to the control collection of gbOptions.

cbIgnoreCase

PropertyValue
Text"Ignore Case"
Location16, 16

cbRightToLeft

PropertyValue
Text"Right to Left"
Location220, 16

Now, for the buttons...

btnCancel

PropertyValue
DialogResultCancel
Location137, 336
Text"C&lose"

Write a procedure to handle the OnClick event of the btnCancel control contains the following code:

Application.Exit()

btnMatch

PropertyValue
Location317, 336
Text"&Match"

Write a procedure to handle the OnClick event of the btnMatch control contains the following code:

Dim m As System.Text.RegularExpressions.Match
Dim lvi As ListViewItem
Dim re As System.Text.RegularExpressions.Regex

'Make sure our program doesn't act ugly 
'when we get an invalid regular expression
Try
    re = New System.Text.RegularExpressions.Regex(txtRegExp.Text)
Catch
    MsgBox("Invalid Regular Expression")
    Exit Sub
End Try

Dim opt As New System.Text.RegularExpressions.RegexOptions()

If txtRegExp.Text.Length <= 0 Then Exit Sub

If txtSearchString.Text.Length <= 0 Then Exit Sub

If cbIgnoreCase.Checked = True And cbRightToLeft.Checked = True Then
    m = re.Match(txtSearchString.TexttxtRegExp.Text_
                 opt.IgnoreCase Or opt.RightToLeft)
ElseIf cbIgnoreCase.Checked = True And cbRightToLeft.Checked = False Then
    m = re.Match(txtSearchString.TexttxtRegExp.Textopt.IgnoreCase)
ElseIf cbIgnoreCase.Checked = False And cbRightToLeft.Checked = True Then
    m = re.Match(txtSearchString.TexttxtRegExp.Textopt.RightToLeft)
Else
    m = re.Match(txtSearchString.TexttxtRegExp.Textopt.None)
End If

lvResults.Items.Clear()

If m.Captures.Count > 0 Then

    Do While m.Success = True
        lvi = New ListViewItem(m.Index)
        lvi.SubItems.Add(m.Value)

        lvResults.Items.Add(lvi)
        m = m.NextMatch()
    Loop

Else

    lvi = New ListViewItem("-1")
    lvi.SubItems.Add("No matches were found.")
    lvResults.Items.Add(lvi)

End If
Generated using PrettyCode.Encoder

btnTest

PropertyValue
Location224, 336
Text"&Test"

Write a procedure to handle the OnClick event of the btnTest control contains the following code:

Dim re As System.Text.RegularExpressions.Regex

'Make sure our program doesn't act ugly 
'when we get an invalid regular expression
Try
    re = New System.Text.RegularExpressions.Regex(txtRegExp.Text)
Catch
    MsgBox("Invalid Regular Expression")
    Exit Sub
End Try

MsgBox(re.IsMatch(txtSearchString.Text))
Generated using PrettyCode.Encoder

We're done! Click run, and enjoy your own regular expressions checker.

Part two of this article will explain how to make this application save regular expressions.

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:2.58823529411766 out of 5
 17 people have rated this page
Article Score14171
Sponsored Links