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

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

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.

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
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

FunctionQuestion it answersReturns
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 matchThe cleaned string
PySparkSpark SQL · Filter, extract every number, clean

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_all takes the pattern as a column, so wrap it in F.lit(...); a plain string would be read as a column name.
  • regexp_replace with \D (any non-digit) and an empty replacement keeps only digits: the standard way to clean phone numbers.
PySparkSpark SQL · Recipes on contact data

Input: contacts

namephoneemail
Asha+91 98765-43210asha@gmail.com
Ben(080) 4123 9876ben@corp.co.in
Chitra98-76-54chitra@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

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"

Can \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

regexp_extract stops at the first match: 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

GoalPatternGroup
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)^erroruse 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.

  1. Get the 6-digit PIN code from "MG Road, Bengaluru 560001".
    Show answerregexp_extract(address, r"(\d{6})", 1). For stricter matching, r"\b(\d{6})\b" skips 7-digit numbers.
  2. Keep rows whose status is exactly "done" or "closed", in any case.
    Show answerfilter(F.col("status").rlike(r"(?i)^(done|closed)$")). Without ^ and $, "not done" would also pass.
  3. From "user=asha; role=admin; team=data", get the role.
    Show answerregexp_extract(settings, r"role=(\w+)", 1) gives admin. Use r"role=([^;]+)" if values can contain spaces.
  4. Turn "98765 - 43210" and "98765-43210" into "9876543210".
    Show answerregexp_replace(phone, r"\D", ""): replace every non-digit with nothing.
  5. Check that a product code is 3 capital letters, a dash and 4 digits, like ABC-1234.
    Show answerrlike(r"^[A-Z]{3}-\d{4}$"). The anchors make it a full-value check.

Questions people usually still have

QuestionAnswer
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 the r, 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 select before running it on a whole table. Sites like regex101.com (choose the Java flavour) show what each piece matches.
Why this matters: Spark runs regex inside the JVM on every row, far faster than a Python UDF doing the same work. Still, parsing billions of rows costs real CPU: extract once into proper columns and store them, rather than re-parsing raw text in every query.

Common mistakes

  • Expecting null when nothing matches — regexp_extract("Order shipped", r"#(\d+)", 1) returns "", so count(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. Write F.nullif(x, F.lit("")).
  • Greedy .* swallowing too much — On "[db] timeout [retry]", r"\[(.*)\]" captures db] timeout [retry. Use .*? or a "not this character" class: r"\[([^\]]+)\]" captures db.
  • Single backslashes in SQL — In SQL, '\d+' becomes d+ 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?"
An empty string, not null. Convert with 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."
Spark uses Java regular expressions. Most syntax is the same, but some features differ (for example named groups and lookbehind limits), and backslashes need raw strings in Python so they reach Java intact.

Check yourself

3 questions

What 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

See all 7 problems →

Keep going

Up next · new module: Beyond built-ins · 7 min read
UDFs and pandas UDFs
When a Python function is the only way, how to write it, and why built-ins are much faster.

Related lessons

Previous: Regular expressions from zero

Primary sources: functions.regexp_extract · functions.regexp_extract_all · Java Pattern syntax