Skip to content
Silver 8 min read · Strings 2 practice problems ↓

Regular expressions from zero

Messy text hides useful fields: an order number in a note, a level in a log line, a domain in an email. A regular expression is a short pattern that finds them. This lesson starts from zero and teaches the dozen symbols that cover almost every real pattern, and how to read and build one piece by piece.

Step 1 · PySpark functions · Silver · Reshape and refine, lesson 6 of 7

Read first: select (skip if you know it)

In plain words first

Describe an Indian number plate to a friend: "two letters, two digits, one or two letters, four digits". You did not list every plate, yet your friend can now spot one in a crowd.

A regular expression is that description in a short code Spark can follow: [A-Z]{2}\d{2} means "two capital letters, then two digits".

What a regex is

So the pattern #\d+ reads, left to right: a #, then a digit (\d), then "one or more of that" (+). In Order #4521 shipped it finds #4521.

Tip: do not memorise these. The three tables below cover almost every pattern; come back to them.

The building blocks

1. What to match

WriteMatchesExample
abcExactly these charactersshipped matches "shipped"
.Any single characterc.t matches "cat", "cut", "c9t"
\dA digit, 0 to 9\d\d matches "42"
\wA "word" character: letter, digit or underscore\w matches "a", "Z", "7", "_"
\sA space, tab or line breaka\sb matches "a b"
[abc]One of the listed charactersgr[ae]y matches "grey" and "gray"
[a-z], [0-9]One character in a range[A-Z] matches one capital letter
[^abc]Any character except those listed[^,] matches anything but a comma
\D, \W, \SThe opposite of \d, \w, \s\D matches any non-digit

2. How many

These go right after the thing they repeat.

WriteMeansExample
+One or more\d+ matches "7", "42", "4521"
*Zero or more\d* also matches nothing at all
?Optional: zero or onecolou?r matches "color" and "colour"
{4}Exactly 4\d{4} matches a year like "2025"
{2,4}Between 2 and 4\d{2,4} matches "12", "123", "1234"

3. Where, which part, and alternatives

WriteMeansExample
^Start of the text^ERROR only matches if the text begins with ERROR
$End of the text\.csv$ matches names ending in .csv
( )A capture group: the part you want back#(\d+) captures "4521" without the #
a|bEither a or b(shipped|cancelled)
\"Take the next character literally"\. is a real dot, \[ a real bracket
(?i) at the startIgnore upper and lower case(?i)order matches "Order" and "ORDER"

The characters that need a backslash to be matched literally are . [ ] ( ) { } * + ? ^ $ | \. Everything else, including #, @, -, : and spaces, matches itself.

Reading a pattern, piece by piece

# · a literal

# is not special, so it matches the character # itself.

\d · one digit

\d matches one digit: the 4 after the #.

+ · or more

+ repeats the digit "one or more" times, as many as possible: 4521. It stops at the space, which is not a digit.

( ) · keep it

The brackets make \d+ capture group 1. The whole match is #4521 (group 0); group 1 is just 4521, which is what you usually want.

The command

F.regexp_extract("note", r"#(\d+)", 1)   # "4521"
F.regexp_extract("note", r"#(\d+)", 0)   # "#4521"

Run it: an order number

PySparkSpark SQL

Input: orders

note
Order #4521 shipped to Pune on 2025-03-14
order #77 cancelled
Refund for ORDER #9032 on 2025-04-02
no order number here
from pyspark.sql import functions as F
result = orders.select(
    "note",
    F.regexp_extract("note", r"#(\d+)", 1).alias("order_id"),
)
SELECT note,
       regexp_extract(note, '#(\\d+)', 1) AS order_id
FROM orders

The last row has no # followed by digits. What Spark returns then (an empty string, not nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →) is the first trap in the next lesson.

Building a pattern step by step

Real patterns are built the same way: match a little, check it, add the next piece. Goal: from 2025-03-01 ERROR [db] timeout after 30s, get the day, the level and the component.

Step 1 · the date

A date is 4 digits, a dash, 2 digits, a dash, 2 digits. Wrap it in brackets to capture it as group 1.

The command

r"(\d{4}-\d{2}-\d{2})"

Step 2 · the level

After the date comes a space, then a word (ERROR, INFO, WARN). \w+ is "one or more word characters"; capture it as group 2.

The command

r"(\d{4}-\d{2}-\d{2}) (\w+)"

Step 3 · the component

Then a space and a word inside square brackets. Square brackets are special in regex, so escape them as \[ and \]. The word inside is group 3.

The command

r"(\d{4}-\d{2}-\d{2}) (\w+) \[(\w+)\]"

Step 4 · use it

Use the same pattern three times, with groups 1, 2 and 3.

The command

pattern = r"(\d{4}-\d{2}-\d{2}) (\w+) \[(\w+)\]"
F.regexp_extract("raw", pattern, 2)   # "ERROR"
PySparkSpark SQL

Input: logs

raw
2025-03-01 ERROR [db] timeout after 30s
2025-03-01 INFO [api] request ok
2025-03-02 WARN [cache] miss rate 12%
corrupted line
from pyspark.sql import functions as F
pattern = r"(\d{4}-\d{2}-\d{2}) (\w+) \[(\w+)\]"
result = logs.select(
    F.regexp_extract("raw", pattern, 1).alias("day"),
    F.regexp_extract("raw", pattern, 2).alias("level"),
    F.regexp_extract("raw", pattern, 3).alias("component"),
)
SELECT regexp_extract(raw, '(\\d{4}-\\d{2}-\\d{2}) (\\w+) \\[(\\w+)\\]', 1) AS day,
       regexp_extract(raw, '(\\d{4}-\\d{2}-\\d{2}) (\\w+) \\[(\\w+)\\]', 2) AS level,
       regexp_extract(raw, '(\\d{4}-\\d{2}-\\d{2}) (\\w+) \\[(\\w+)\\]', 3) AS component
FROM logs

Counting groups, optional parts and (?: )

  • Groups are numbered by their opening bracket, counting from the left: the first ( is group 1, the second ( is group 2, and so on, even when one group is inside another.
  • If a group is optional (followed by ?) and the text does not have that part, the group is "" while the rest of the match still works.
  • (?: ) groups without capturing: use it to apply ? or | to several characters without adding a group number.

Example: names that may or may not start with a title. (?:(Mr|Ms|Dr)\. )? means "optionally, a title, a dot and a space"; the outer (?: ) makes the whole part optional without becoming a group, so the title is group 1, the first name group 2 and the last name group 3.

PySparkSpark SQL

Input: people

full_name
Mr. Arjun Rao
Ms. Priya Nair
Dr. Sam Lee
Kiran Das
from pyspark.sql import functions as F
pattern = r"^(?:(Mr|Ms|Dr)\. )?(\w+) (\w+)$"
result = people.select(
    "full_name",
    F.regexp_extract("full_name", pattern, 1).alias("title"),
    F.regexp_extract("full_name", pattern, 2).alias("first_name"),
    F.regexp_extract("full_name", pattern, 3).alias("last_name"),
)
SELECT full_name,
       regexp_extract(full_name, '^(?:(Mr|Ms|Dr)\\. )?(\\w+) (\\w+)$', 1) AS title,
       regexp_extract(full_name, '^(?:(Mr|Ms|Dr)\\. )?(\\w+) (\\w+)$', 2) AS first_name,
       regexp_extract(full_name, '^(?:(Mr|Ms|Dr)\\. )?(\\w+) (\\w+)$', 3) AS last_name
FROM people

Kiran Das has no title, so title is "", but the first and last names are still found. In regexp_replace, groups can be reused in the replacement as $1, $2: regexp_replace(code, r"([A-Z]+)-(\d+)", "$2/$1") turns IN-2045 into 2045/IN.

Contains or exact match: ^, $ and \b

rlike and regexp_extract look for the pattern anywhere in the text. That is often not what a validation rule means. Compare three versions of "an IN- code with 4 digits":

PySparkSpark SQL

Input: codes

code
IN-2045
order IN-2045 shipped
IN-20456
in-2045
XIN-2045
from pyspark.sql import functions as F
result = codes.select(
    "code",
    F.col("code").rlike(r"IN-\d{4}").alias("contains"),
    F.col("code").rlike(r"^IN-\d{4}$").alias("is_exactly"),
    F.col("code").rlike(r"\bIN-\d{4}\b").alias("as_a_word"),
)
SELECT code,
       code RLIKE 'IN-\\d{4}'           AS contains,
       code RLIKE '^IN-\\d{4}$'         AS is_exactly,
       code RLIKE '\\bIN-\\d{4}\\b'     AS as_a_word
FROM codes
PatternMeansSurprise it avoids
IN-\d{4}Somewhere in the textNone: IN-20456 and XIN-2045 also pass
^IN-\d{4}$The whole value, nothing before or afterRejects extra digits and surrounding text
\bIN-\d{4}\bAs a separate word inside longer text\b is a word boundary: the edge between a word character and anything else

For data-quality checks ("is this a valid code?"), almost always use ^...$. Note that in-2045 fails every version: regex is case-sensitive unless you add (?i).

Common mistakes

  • Forgetting to escape . [ ] ( ) — r"a.csv" also matches "abcsv", because . means "any character". Write r"a\.csv" for a real dot.
  • Group number off by one — On "Order #4521" with r"#(\d+)", group 0 is "#4521" (the whole match) and group 1 is "4521".
  • Testing a pattern only on the rows that work — A pattern that finds #4521 may also match # in a hashtag. Try it on the awkward rows too: missing values, extra spaces, other formats.

Key takeaways

  • Build a pattern a piece at a time: match a little, check it on real rows, then add the next piece.
  • Patterns search anywhere in the value: anchor with ^...$ for "the whole value" and \b for a separate word.
  • (?: ) groups parts for ? or | without a number, so the groups after it keep their numbers.
  • Start a pattern with (?i) to ignore upper and lower case.

Interview prep

THE QUESTION

"Write a pattern that checks a value is exactly an order code like IN-2045, and explain it."

^IN-\d{4}$: ^ and $ anchor the start and end, IN- matches itself, \d{4} is exactly four digits. Without the anchors, order IN-2045 shipped and IN-20456 would pass too. It is case-sensitive unless the pattern starts with (?i).

Avoid: reciting symbols without anchors: a pattern that "works" on the happy row but also accepts IN-20456 or text around the code.

Follow-ups · answer out loud, then open

Follow-up"What is the difference between (\d+) and (?:\d+)?"
Both group the digits, so a quantifier or | can apply to the whole group. Only the first is a capture group with a number you can extract; (?: ) groups without numbering, so the groups after it keep their numbers.
Scenario"Names arrive as 'Mr. Arjun Rao', 'Dr. Sam Lee' or just 'Kiran Das'. Capture the first name."
Make the title optional and non-capturing: ^(?:(?:Mr|Ms|Dr)\. )?(\w+). The optional group swallows a title when there is one, and group 1 is always the first name.
Trap"\d means a digit, so the pattern 'a.b' matches only a.b."
An unescaped dot means "any character", so a.b also matches axb and a-b. Escape it as \. to match a real dot.

Check yourself

5 questions

What does the pattern \d{3} match?

Show the answer

Exactly three digits in a row. \d is one digit and {3} means exactly three of them.

In #(\d+), which part is returned with group index 1?

Show the answer

4521. Group 1 is what the first brackets matched: the digits. Group 0 is the whole match, including #.

Which value passes rlike(r"^IN-\d{4}$")?

Show the answer

IN-2045. With ^ and $ the whole value must be IN- and exactly four digits; regex is case-sensitive, so in-2045 fails.

In ^(?:(Mr|Ms)\. )?(\w+), which group number is the first name?

Show the answer

2. (?: ) does not count. (Mr|Ms) is group 1 and (\w+) is group 2.

Which pattern matches a literal dot followed by csv at the end of a file name?

Show the answer

\.csv$. An unescaped . means "any character"; \. is a real dot, and $ anchors the end.

Practise this

Interview problems on strings, graded on hidden tests

Keep going

Up next · Reshape and refine · lesson 7 of 7 · 8 min read
regexp_extract
Extract, filter, replace and collect with a regular expression, and what you get when nothing matches.

Related lessons

Previous: trunc / add_months

Primary sources: Java Pattern syntax · functions.rlike