Overview

The FSAs and Regular Expressions topic introduces the core operators (concatenation, union, Kleene star) and the everyday regex additions ?, +, ., [ ] and ( ). This invitational topic adds the rest of the toolkit used by real programming languages: shorthand character classes such as \d and \w, exact repetition counts with { }, anchors that pin a match to the start or end of a line, word boundaries, and backreferences that force part of a string to repeat.

Questions give you a pattern and a list of candidate strings and ask which ones match, or describe a set of strings and ask you to write a pattern. The skill is reading a dense pattern piece by piece and testing each candidate methodically.

Key Concepts:

  • A backslash turns a letter into a character class (\d, \w, \s) or turns a special symbol into a literal (\., \*).
  • Uppercase versions negate: \D is anything that is not a digit.
  • ^ and $ anchor the pattern to the beginning and end of the string; without them a pattern may match anywhere inside a longer string.
  • Parentheses capture what they match, and \1, \2, ... refer back to those captures.

Key Concepts

Useful Patterns

PatternMeaningExample regexMatchesDoes not match
\dAny digit; same as [0-9]\d\d\d1231-3
\DAny character that is not a digit\d\D\d1-3123
\wWord character: letter, digit or underscore; same as [a-zA-Z0-9_]\w\w\wa_Aa-A
\WAny character that is not a word character\W\W\W+-$+_@
\sWhitespace: space, tab or line break\d\s\w1 a1ab
\SAny character that is not whitespace\w\w\w\w\S\dTest#1test 1
\bWord boundary: the position between a word character and a non-word character (or the start/end of the string)\bis\bis; (the word "is")This island
{n}, {min,}, {min,max}Repeat the preceding element exactly n times, at least min times, or between min and max timesabc{2}abccabc
.*Zero or more of any character.*abbb, the empty string
.+One or more of any character.+a, abbccthe empty string
^Anchor: the start of the string^The\s\w+The contestOne contest
$Anchor: the end of the string\d{4}\sACSL$2020 ACSL2020 STAR
\Escape: match a special character literally\w\w\w\.cat.lion
( )Group and capture^(file.+)\.docx$file_graphs.docxdata.docx
\1, \2Backreference: repeat exactly what group 1 (or 2) capturedr(\w)g\1xregex (group 1 is e)regxx

Reading a Pattern

  1. Split the pattern into tokens: each character class, literal, group and quantifier.
  2. Note which quantifier belongs to which token. \d{3} is three digits; (ab){2} is "abab".
  3. Check for anchors. With ^...$ the whole string must be consumed; otherwise the pattern only has to appear somewhere in the string.
  4. For backreferences, write down what each group captured for the specific string, then check that the later text is identical (including case).
  5. Test every candidate string against every token, in order. Reject as soon as one token cannot be satisfied.

Backreferences in Detail

Groups are numbered by the position of their opening parenthesis, left to right. In (\d\d)\+(\d\d)=\2\+\1, group 1 is the first two digits and group 2 the second two. The string 20+21=21+20 matches because after the equals sign the text is group 2 then group 1. The string 20+21=20+21 does not, because the order is wrong. Backreferences must match the captured text, not just the same kind of text: if group 1 captured "e", \1 matches only "e".

Examples

Example 1: Matching a domain name

Which of these strings match ^w{3}\.([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])+\.)+[a-z0-9][-a-z0-9]{0,61}[a-z0-9]?

  1. www.google.com
  2. www.-petsmart.com
  3. www.edu-.ro
  4. www.google.co.in
  5. www.examples.c.net
  6. www.edu.training.computer-science.org
  7. www.everglades_holidaypark.com

Take the pattern apart:

  • ^w{3}\.: the string starts with exactly "www" and a literal dot.
  • ([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])+\.)+: one or more domain labels, each followed by a dot. A label starts with a lowercase letter or digit, may contain hyphens in the middle, ends with a letter or digit, and is at least 2 characters long (the inner group must appear at least once and itself ends with a letter or digit).
  • [a-z0-9][-a-z0-9]{0,61}[a-z0-9]: the final top-level label, with the same rules and no trailing dot.

String 2 has a label starting with a hyphen, string 3 has a label ending with a hyphen, string 5 has the one-character label "c", and string 7 contains an underscore, which is not allowed.

Matches: 1, 4 and 6

Example 2: Writing a pattern from a description

Describe strings that: contain only lowercase letters and the character "."; start and end with the same letter; and consist of one to three vowels, then zero or more dots, then at least one consonant, between those matching end letters.

  1. ([a-z]) captures the first letter as group 1.
  2. [aeiou]{1,3} matches one to three vowels.
  3. \.* matches zero or more literal dots (the backslash is needed because a bare dot means "any character").
  4. [b-df-hj-np-tv-z]+ matches one or more consonants. The ranges skip over each vowel.
  5. \1 requires the string to end with the same letter that group 1 captured.

Pattern: ([a-z])[aeiou]{1,3}\.*[b-df-hj-np-tv-z]+\1

Example 3: Word boundaries

Which strings contain a match for \bcat\b? "the cat sat" does, because "cat" is surrounded by spaces. "cat's" does, because the apostrophe is a non-word character, so there is a boundary after the t. "concatenate" and "bobcat" do not, because the letters on either side of "cat" are word characters, so there is no boundary.

Practice Problems

Enter the numbers of the matching strings separated by commas, for example 1,3,5. Every pattern below is anchored with ^ and $ unless stated otherwise, so the whole string must match.

Problem 1 Junior

Which of the following strings match the pattern ^\d{3}-\d{4}$?

  1. 555-1234
  2. 5551234
  3. 55-12345
  4. 123-4567
  5. 123-45678

Problem 2 Junior

Which of the following strings match the pattern ^[A-Z]\w+\s\d+$?

  1. Room 101
  2. room 7
  3. A1 22
  4. Hall_B 3
  5. Room101

Problem 3 Intermediate

Which of the following strings match the pattern ^(\w+)\s\1$?

  1. ha ha
  2. ha haha
  3. go Go
  4. 22 22
  5. hi_hi hi_hi

Problem 4 Intermediate

The pattern \bcat\b is not anchored. Which of the following strings contain a match for it?

  1. cat
  2. concatenate
  3. the cat sat
  4. cat's
  5. bobcat

Problem 5 Senior

Which of the following strings match the pattern ^(\w)(\w)\w*\2\1$?

  1. abccba
  2. abba
  3. abab
  4. xy12yx
  5. aaa
  6. a-bb-a