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
On this page
Show code in
Every code block on the page follows this.
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.
The building blocks
1. What to match
| Write | Matches | Example |
|---|---|---|
abc | Exactly these characters | shipped matches "shipped" |
. | Any single character | c.t matches "cat", "cut", "c9t" |
\d | A digit, 0 to 9 | \d\d matches "42" |
\w | A "word" character: letter, digit or underscore | \w matches "a", "Z", "7", "_" |
\s | A space, tab or line break | a\sb matches "a b" |
[abc] | One of the listed characters | gr[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, \S | The opposite of \d, \w, \s | \D matches any non-digit |
2. How many
These go right after the thing they repeat.
| Write | Means | Example |
|---|---|---|
+ | One or more | \d+ matches "7", "42", "4521" |
* | Zero or more | \d* also matches nothing at all |
? | Optional: zero or one | colou?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
| Write | Means | Example |
|---|---|---|
^ | 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|b | Either a or b | (shipped|cancelled) |
\ | "Take the next character literally" | \. is a real dot, \[ a real bracket |
(?i) at the start | Ignore 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
\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
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
The command
r"(\d{4}-\d{2}-\d{2})"Step 2 · the level
\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
\[ and \]. The word inside is group 3.The command
r"(\d{4}-\d{2}-\d{2}) (\w+) \[(\w+)\]"Step 4 · use it
The command
pattern = r"(\d{4}-\d{2}-\d{2}) (\w+) \[(\w+)\]" F.regexp_extract("raw", pattern, 2) # "ERROR"
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.
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":
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
| Pattern | Means | Surprise it avoids |
|---|---|---|
IN-\d{4} | Somewhere in the text | None: IN-20456 and XIN-2045 also pass |
^IN-\d{4}$ | The whole value, nothing before or after | Rejects extra digits and surrounding text |
\bIN-\d{4}\b | As 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". Writer"a\.csv"for a real dot. - Group number off by one — On
"Order #4521"withr"#(\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
#4521may 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\bfor 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+)?"
Scenario"Names arrive as 'Mr. Arjun Rao', 'Dr. Sam Lee' or just 'Kiran Das'. Capture the first name."
^(?:(?: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."
Check yourself
5 questionsWhat 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 readregexp_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