Course contentsShow
← Computer Science
Lesson 1768 of 2,87240. Theory of Computation: Regular LanguagesFree lesson

Building Regular Expressions from Patterns

Practice constructing regular expressions for common string patterns like specific prefixes, suffixes, and substrings.

Building Regular Expressions from Patterns

You'll learn how to construct regular expressions that match strings with specific prefixes, suffixes, and substrings.

The Core Idea

Now that you understand regular expression syntax and semantics, it's time to practice building them for common patterns. Think of this as learning to write sentences in a new language—you know the grammar, and now you're forming meaningful expressions to describe real-world string patterns.

Pattern Construction Techniques

Prefixes

To match strings that start with a specific pattern, place that pattern at the beginning with .* after it (or use concatenation with the Kleene star on the alphabet).

For example, to match all strings starting with abc:

  • abc(a|b|c)* matches strings over alphabet {a,b,c} that begin with "abc"

Suffixes

To match strings that end with a specific pattern, use .* before the pattern.

For example, to match all strings ending with xyz:

  • (a|b|c)*xyz matches strings over {a,b,c} that conclude with "xyz"

Substrings

To match strings containing a specific pattern anywhere, surround it with .* on both sides.

For example, to match strings containing hello:

  • .*hello.* or more formally (a|b|...)*hello(a|b|...)*

Combinations

You can combine these! For strings starting with a and ending with b:

  • a(a|b)*b ensures the first character is a and the last is b

Think Like a Pattern Builder

Ask yourself: "Where must my pattern appear?" Then use Kleene star to allow arbitrary content before, after, or around it.

Key Takeaway: Build regular expressions by anchoring your required pattern (prefix/suffix/substring) and using Kleene star to handle the flexible parts—this systematic approach covers most common string-matching scenarios.