Your first Regex tutorial - matching numbers only
Posted: Fri Apr 29, 2011 1:52 pm
Regular Expressions can be confusing for many people but when you actually get your head around it it isn't that bad I am still learning it myself but I want to show you guys something thats easy to do
Ok so what I am going to show you is I have a textbox and an error provider and a button.
If the textbox contains anything that ISNT a number then the error provider will tell you that you can only use numbers
when you press the button if you only used numbers then a msgbox will pop up saying it was only numbers
Code:
the [0-9] is what it is looking for, and the * indicates that it can match any amount of numbers 0 to what ever number you want, for example it doesnt matter if you have 094096409640 or 358748574 as long as it is a number it is fine.
![Image]()
![Image]()
Ok so what I am going to show you is I have a textbox and an error provider and a button.
If the textbox contains anything that ISNT a number then the error provider will tell you that you can only use numbers
when you press the button if you only used numbers then a msgbox will pop up saying it was only numbers
Code:
Code: Select all
The "^[0-9]*$" is the expression we are using. the ^ indicates the beginning of the input, and the $ indicates the end of the input.Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Numregex As New Regex("^[0-9]*$")
If Numregex.IsMatch(TextBox1.Text) Then
ErrorProvider1.SetError(TextBox1, [String].Empty)
MsgBox("It only contained numbers, good")
Else
ErrorProvider1.SetError(TextBox1, "You can only use numbers")
End If
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim Numregex As New Regex("^[0-9]*$")
If Numregex.IsMatch(TextBox1.Text) Then
ErrorProvider1.SetError(TextBox1, [String].Empty)
Else
ErrorProvider1.SetError(TextBox1, "You can only use numbers")
End If
End Sub
End Class
the [0-9] is what it is looking for, and the * indicates that it can match any amount of numbers 0 to what ever number you want, for example it doesnt matter if you have 094096409640 or 358748574 as long as it is a number it is fine.

