SIMS 255: Lab 12
Wednesday, November 13, 2002
Regular Expressions
In today's lab we'll practice string matching using regular expressions. The Regular Expression Tester at ASPSmith.com will help. Here's an example of how to use it:
-
Go to the Regular Expression Tester.
-
Type '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' (without the quotes) in the Regular Expression field.
-
Type 'Phone at SIMS is 642-1464.' in the Text To Check field.
-
Click the Match button. The Result field indicates that a match was found.
-
To find out what portion(s) of the string matched, click the Replace button. Red square brackets replace the parts of the string that match the regular expression. In this example, it indicates that the regular expression found a match for the phone number.
Exercises
-
The example regular expression above is not a very efficient or robust expression for matching a phone number. Use counters/repeaters to avoid simply typing '[0-9]' over and over.
-
Modify it again so it can find a phone number that optionally includes an area code. Include the ability to find phone numbers that have parentheses around the area code, or separate the area code, prefix and suffix with dashes, and/or periods, and/or spaces.
-
Write a regular expression that can match email addresses. Examples from last Thursday's lecture:
-
hearst@sims.berkeley.edu
-
Wacky@yahoo.com
-
Vip@ic-arda.gov
-
Write a regular expression that can match one or more document names, of one or more file types. For example:
-
myfile.doc
-
myFile.txt
-
My File.java
-
lab12.html
[You can specify the file types, such as 'doc' and 'txt'. Your expression doesn't need to match every possible file type.]
-
Assume you are writing a Java compiler. Write regex that can verify Java syntax for variable declarations, such as:
-
int i = 34;
-
String myString = "this is a string!";
[Your regex should be able to handle multiple spaces and other white space.]
LZ -- last modified 11/12/02