regexp_extract
Once you can write a pattern, four Spark functions put it to work: regexp_extract pulls a piece out, rlike filters, regexp_replace cleans, and regexp_extract_all collects every match. This lesson shows each one, the empty-string trap when nothing matches, and the backslash rules that trip everyone up.
Step 1 · PySpark functions · Silver · Reshape and refine, lesson 7 of 7
On this page
Show code in
Every code block on the page follows this.
Read first: Regular expressions from zero (skip if you know it)
In plain words first
A pattern is only a description, like "two letters then four digits". The functions are what you do with it: cut the matching piece out (extract), keep the rows that contain it (rlike), swap it for something else (replace), or collect every match (extract all). Regular expressions from zero teaches the patterns.
When nothing matches: empty string, not null
For corrupted line all three columns above are "". That matters: count("level") counts empty strings, and coalesce will not replace them. Turn them into real nullsnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → with F.nullif(..., F.lit("")) (Spark 3.5+), or F.when(x == "", None).otherwise(x) on older versions. Note the F.lit: nullif treats a plain "" as a column name and fails.
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 order_id = F.regexp_extract("note", r"#(\d+)", 1) result = orders.select("note", F.nullif(order_id, F.lit("")).alias("order_id"))
SELECT note, nullif(regexp_extract(note, '#(\\d+)', 1), '') AS order_id FROM orders
The four regex functions
| Function | Question it answers | Returns |
|---|---|---|
col.rlike(p) | Does the text match? | true / false: use it in filter |
regexp_extract(col, p, n) | What did group n match (first match only)? | A string, "" if no match |
regexp_extract_all(col, p, n) | What did group n match, every time? | An arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → (Spark 3.1+ SQL, 3.5+ Python) |
regexp_replace(col, p, new) | Replace every match | The cleaned string |
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 .filter(F.col("note").rlike(r"(?i)order #\d+")) .select( "note", F.regexp_extract_all("note", F.lit(r"(\d+)"), 1).alias("numbers"), F.regexp_replace("note", r"\d", "*").alias("masked"), ))
SELECT note, regexp_extract_all(note, '(\\d+)', 1) AS numbers, regexp_replace(note, '\\d', '*') AS masked FROM orders WHERE note RLIKE '(?i)order #\\d+'
(?i)made the filter keep "Order", "order" and "ORDER".- In Python,
regexp_extract_alltakes the pattern as a column, so wrap it inF.lit(...); a plain string would be read as a column name. regexp_replacewith\D(any non-digit) and an empty replacement keeps only digits: the standard way to clean phone numbers.
Input: contacts
| name | phone | |
|---|---|---|
| Asha | +91 98765-43210 | asha@gmail.com |
| Ben | (080) 4123 9876 | ben@corp.co.in |
| Chitra | 98-76-54 | chitra@yahoo.com |
from pyspark.sql import functions as F result = contacts.select( "name", F.regexp_replace("phone", r"\D", "").alias("digits"), F.regexp_extract("email", r"@(.+)$", 1).alias("domain"), )
SELECT name, regexp_replace(phone, '\\D', '') AS digits, regexp_extract(email, '@(.+)$', 1) AS domain FROM contacts
How the regex engine searches
It helps to picture what Spark does with your pattern. It does not look at the text as a whole; it tries the pattern at each position, from left to right, and stops at the first place where the whole pattern fits.
Position 1 · "R"
\d+ start at R? R is not a digit, so no. Move one character right.Positions 2-5 · "oom "
o, o, m and the space are not digits either. Keep moving.Position 6 · "1"
1 is a digit, so the match starts here. + keeps taking digits: 2 also fits, , does not. The match is 12.Done · first match wins
12. The 3 later in the text is never looked at. To get every match (12 and 3), use regexp_extract_all.Two rules follow from this: the leftmost match wins, and quantifiers like + and * take as much as they can from that starting point (unless you make them lazy with ?, covered below).
Greedy vs lazy: the .* trap
+ and * grab as much as they can. On [urgent] call back [today], the pattern \[(.*)\] captures urgent] call back [today: the .* runs to the last ]. Add a ? to make it lazy, stopping at the first possible place: \[(.*?)\] captures urgent. Even clearer is to say what is allowed: \[([^\]]+)\], "one or more characters that are not a closing bracket".
Rules inside [ ]
- Inside square brackets most special characters lose their meaning:
[.]is a real dot and[$]a real dollar sign. - A
-between two characters is a range ([0-9]); put it first or last to mean a literal dash:[\w-]is "a word character or a dash". ^means "not" only as the first character:[^0-9]. Anywhere else it is a literal^.- Shorthands work inside brackets too:
[\d.]is "a digit or a dot", useful for prices like 12.50. - To include a
], escape it:[^\]]is "anything except a closing bracket".
Copy-paste recipes
| Goal | Pattern | Group |
|---|---|---|
| Email domain | @(.+)$ | 1 |
| First number in the text | (\d+) | 1 |
| A date like 2025-03-14 | (\d{4}-\d{2}-\d{2}) | 1 |
| A URL parameter, e.g. id | [?&]id=([^]+) | 1 |
| Text inside [ ] | \[([^\]]+)\] | 1 |
| Text inside ( ) | \(([^)]+)\) | 1 |
| File extension | \.(\w+)$ | 1 |
| Starts with error, any case | (?i)^error | use with rlike |
| Keep only digits | \D (replace with "") | use with regexp_replace |
| Collapse repeated spaces | \s+ (replace with " ") | use with regexp_replace |
Your turn: five small exercises
Try writing each pattern before opening the answer. You can test it by editing any runnable example above.
- Get the 6-digit PIN code from
"MG Road, Bengaluru 560001".Show answer
regexp_extract(address, r"(\d{6})", 1). For stricter matching,r"\b(\d{6})\b"skips 7-digit numbers. - Keep rows whose status is exactly "done" or "closed", in any case.
Show answer
filter(F.col("status").rlike(r"(?i)^(done|closed)$")). Without^and$, "not done" would also pass. - From
"user=asha; role=admin; team=data", get the role.Show answer
regexp_extract(settings, r"role=(\w+)", 1)givesadmin. User"role=([^;]+)"if values can contain spaces. - Turn
"98765 - 43210"and"98765-43210"into"9876543210".Show answer
regexp_replace(phone, r"\D", ""): replace every non-digit with nothing. - Check that a product code is 3 capital letters, a dash and 4 digits, like
ABC-1234.Show answer
rlike(r"^[A-Z]{3}-\d{4}$"). The anchors make it a full-value check.
Questions people usually still have
| Question | Answer |
|---|---|
| Is regexregular expression: A short pattern that describes what some text looks like, used to find, check or extract parts of strings. Learn more → case-sensitive? | Yes. Add (?i) at the start of the pattern, or lower-case the column first with F.lower. |
| My pattern matches nothing. How do I debug it? | Shorten it until it matches, then add one piece at a time (the way the log pattern was built above). Check for unescaped . ( ) [ ] and, in SQL, single backslashes. |
| regexp_extract, split or substring? | Fixed positions (first 3 characters): substring. A clean separator (the part after @): split. Anything that needs "a number after a #" or "a word in brackets": regex. |
| How do I match a real backslash, dollar or dot? | Escape it with a backslash: \\, \$, \.. Inside [ ], . and $ need no escape. |
| Does . match a line break? | No. Add (?s) at the start if a value can span several lines. |
| Which regex flavour does Spark use? | Java's java.util.regex. Online testers like regex101.com have a Java option; Python's re is almost identical for everything on this page. |
| Can I get every match, not just the first? | Yes: regexp_extract_all returns an array (then explode it if you need rows). |
| Is regex slow in Spark? | Built-in regex functions are fast. Avoid nested repeats like (a+)+, which can take very long on some inputs, and avoid Python UDFsUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more → for parsing. |
Backslashes in Python and SQL
- In Python, always write patterns as raw strings:
r"\d+". Without ther, Python may treat the backslash itself, and"\b"silently becomes a backspace character. - In Spark SQL string literals, every backslash must be doubled:
'\\d+'. That is why the SQL versions on this page look busier. - Test a new pattern on a few sample rows with
selectbefore running it on a whole table. Sites like regex101.com (choose the Java flavour) show what each piece matches.
Common mistakes
- Expecting null when nothing matches —
regexp_extract("Order shipped", r"#(\d+)", 1)returns"", socount(order_id)still counts that row. Wrap it:F.nullif(..., F.lit("")). - F.nullif(x, "") with a plain string — nullif reads both arguments as columns, so
""means "the column named empty string" and fails with UNRESOLVED_COLUMN. WriteF.nullif(x, F.lit("")). - Greedy .* swallowing too much — On
"[db] timeout [retry]",r"\[(.*)\]"capturesdb] timeout [retry. Use.*?or a "not this character" class:r"\[([^\]]+)\]"capturesdb. - Single backslashes in SQL — In SQL,
'\d+'becomesd+and matches the letter d. Double them:'\\d+'.
Key takeaways
- regexp_extract returns an empty string, not null, when nothing matches: wrap it in
F.nullif(..., F.lit("")). - rlike filters, regexp_replace rewrites, regexp_extract_all returns every match as an array.
.*is greedy and grabs as much as it can; use.*?or a "not this character" class.- Use raw strings (
r"...") in Python, and double every backslash in SQL.
Interview prep
THE QUESTION
"Extract the domain from email addresses and count users per domain."
F.lower(F.regexp_extract("email", r"@(.+)$", 1)): @ is literal, (.+) captures everything after it, $ anchors at the end. Then group by the domain and count. Mention that addresses without an @ give an empty string, so filter them or turn them into null with nullif, and that F.split("email", "@")[1] is a simpler alternative when the data is clean.Avoid: using split on "@" and taking index 1. It breaks on missing or multiple @ signs and gives null-handling surprises.
Follow-ups · answer out loud, then open
Follow-up"What does regexp_extract return when the pattern does not match?"
F.nullif(..., F.lit("")) if you want null, or check with rlike first.Scenario"Extract every hashtag from tweets into an array."
F.regexp_extract_all("text", F.lit(r"#(\w+)"), 1) (Spark 3.1+ in SQL, Python function in 3.5+). Then explode if you need one row per tag.Trap"Spark regex is Python regex."
Check yourself
3 questionsWhat does regexp_extract return when the pattern does not match?
Show the answer
An empty string. It returns an empty string. Use nullif(..., lit("")) to get null.
On "[db] timeout [retry]", what does r"\[(.*)\]" capture in group 1?
Show the answer
db] timeout [retry. .* is greedy: it runs to the last ] it can find. Use .*? or [^\]]+ to stop at the first.
In Spark SQL, how do you write the pattern for one or more digits?
Show the answer
'\\d+'. SQL string literals eat one backslash, so double it to pass \d+ to the regex engine.
Practise this
Problems that use regexp_extract, graded on hidden tests
- Mask Personal Data Before TrainingData Prep for AI Easy
- Parse Application Log LinesStrings Medium
- Parse UTM ParametersStrings Medium
Keep going
Up next · new module: Beyond built-ins · 7 min readUDFs and pandas UDFs
When a Python function is the only way, how to write it, and why built-ins are much faster.
Related lessons
Regular expressions from zeroPySpark functions · 5 min read
String functions
Previous: Regular expressions from zero
Primary sources: functions.regexp_extract · functions.regexp_extract_all · Java Pattern syntax