Sets of Characters
Brackets [] enclose a set of characters. [abc] is the set of letters "a", "b", "c". [A-Z] is the set of upper case letters. [a-z] is the set of lower case letters, [0-9] is the set of digits.
Special characters:
[\^$.|?*+()
If you want to include any of these special characters in a set you must use a backslash in front of them. The sentence should end with [\.\?!] that is, a period, a question mark or an exclamation point. The expression below says that a sentence can have any number (indicated by the *) of the set A-Z, a-z and a space followed by a period, ? or ! Notice that there is a backslash in front of the special characters period and question mark but not in front of the exclamation point.
Dim Sentence As String = "How are you?" 'this would be some input string
Dim SentenceRegex As Regex = New Regex("[A-Za-z ]*[\.\?!]")
Dim M As Match = SentenceRegex.Match(Sentence)
Me.Text = M.ToString = Sentence 'They should be the same if it was accepted
This would not accept "Hello, how are you?" because of the comma. Furthermore, a sentence should start with an upper case letter. Experiment to see if you can add that.
Quantity Specifier
The set of characters is followed by one of the following to indicate how many characters in that set are allowed.
? 0 or 1 time
* 0 or more
+ 1 or more times
{n} n must be an integer where n>=1 item must appear exactly n times.
{n,m} n must be an integer where n>=1, item must appear n to m times.
{n,} where n >= 0, item must appear n or more times.
The example below determines if a string is a valid name for a robot. A robot name must be a letter and a digit followed by a letter and a digit, R2D2 or C3P0 for instance. Notice that the two sets [A-Z] and [0-9] are surrounded by parenthesis and the {2} is outside the parenthesis. This means that there must be exactly 2 instances of a letter followed by a digit.
Dim Robot As String = "R2D2" 'this would be some input string
Dim RobotRegex As Regex = New Regex("([A-Z][0-9]){2}")
Dim M As Match = RobotRegex.Match(Robot)
Me.Text = M.ToString = Robot 'They should be the same if it was accepted
Experiment: Write a regular expression that will accept a phone number. Take into account all of the following: (301)555-1234, 301.555.1234, and 301-555-1234.
Regular expressions are widely used, not just in Visual Basic. Whole books have been written about regular expressions, after trying these examples, if you want to learn more search for "regular expressions" on the internet.