2007-11-19

RegularExpressions Class

The Regex class contains several static methods that allow you to use a regular expression without explicitly creating a Regex object. Using a static method is equivalent to constructing a Regex object, using it once and then destroying it.

Sample Code 1

Imports System.Text.RegularExpressions
' import the namespace

'instantiate the objects
dim oRegex as new regex("test pattern")

'use the object
If oRegex.IsMatch("this is the string to test on") Then
msgbox "Match found"
else
msgbox "Did not find match"
end i


Sample Code 2

//Check for correct format of your name

Dim myMatch As Match = System.Text.RegularExpressions.Regex.Match(InsertYourName, "^[A-Z][a-zA-Z]*$")

If Not myMatch.Success Then

'Name was incorrect

ErrorMessage("Invalid Name", "Message")

txtFname.Focus()

Return

End If


Regular Expressions Elements:

* . Character except a newline character(\n)
* \d Any decimal digit
* \D Any nondigit
* \s Any white-space character
* \S Any Non-white-space charater
* \w Any word character
* \W Any nonword character
* ^ Beginning of string or line
* \A Beginning of string
* $ End of string or line
* \z End of string
* | Matches one of the expressions seprated by the vertical bar; example eee|ttt will match one of eee or ttt (tracing left to right)
* [abc] Match with one of the characters; example [rghy] will match r, g,h or c not any other character.
* [^abc] Match with any of character except in list; example [ghj] will match all character except g,h or k.
* [a-z] Match any character within specified range; example [a - c] will match a, b or c.
* ( ) Subexpression treated as a single element by regular expression elements described in this table.
* ? Match one or zero occurrences of the previous character or subexpression; example a?b will match a or ab not aab.
* * Match zero or more occurences of the previous character or subexpression; example a*b will match b, ab, aab and so on.
* + Match one or more occurences of the previous character or subexpression; example a+b will match ab, aab and so on but not b.
* {n} Match exactly n occurrences of the preceding character;example a{2} will match only aa.
* {n,} Match minimum n occurrences of the preceding character;example a{2,} will match only aa,aaa and so on.
* {n,m} Match minimum n and maximum n occurrences of the preceding character;example a{2, 4} will match aa, aaa, aaaa but not aaaaa.

1 comment:

john said...

The post helps me a lot in to build a better website!