Practice reading, writing, and testing regular expressions for common text matching tasks.
Read each problem carefully. For matching questions, explain why the pattern matches or does not match. Use standard regular expression notation.
Finding text patterns with regex syntax
CS - Grade 9-12
- 1
The regular expression cat is tested against these strings: cat, catalog, scatter, dog. Which strings contain a match, and why?
- 2
Explain the difference between the patterns cat and ^cat$ when matching strings.
- 3
Write a regular expression that matches either color or colour.
- 4
The pattern gr[ae]y is tested against gray, grey, groy, and grAy. Which strings match?
- 5
Write a regular expression that matches a three-digit number such as 042, 107, or 999. It should not match a two-digit or four-digit number if the whole string is being checked.
- 6
A username must start with a letter and then contain 3 to 11 more characters. The remaining characters may be letters, digits, or underscores. Write a regular expression for the whole username.
- 7
For the pattern a+b*, decide whether each string matches the entire pattern: a, ab, aaabb, b, and aaac. Explain your choices.
- 8
What is matched by the regular expression \bcat\b in the sentence The cat sat in the category box?
- 9
Write a regular expression that matches a simple school email address ending in @school.edu. The part before @ must contain one or more lowercase letters, digits, dots, underscores, or hyphens.
- 10
The pattern ^[A-Z]{2}\d{4}$ is used to check ID codes. Which of these match: AB1234, A12345, ab1234, XY9876, and ZQ12B4?
- 11
Explain what the dot means in the pattern h.t. Then give two strings that match and one string that does not match.
- 12
A log file has lines like ERROR: disk full, WARNING: high memory, and INFO: started. Write a regular expression that matches only lines beginning with ERROR: or WARNING:.