Surfalytics
PySpark course overview

DataFrame basics I · Topic 8 Free

Regular expressions: rlike()

Same tasks, other language: the SQL version of this topic.

Data model — the tables you will query
N 1 N 1 N 1 N 1 cohorts id PK INT name TEXT start_date DATE format TEXT students id PK INT name TEXT city TEXT country TEXT cohort_id FK INT background TEXT joined_at DATE courses id PK INT title TEXT category TEXT difficulty TEXT hours INT enrollments id PK INT student_id FK INT course_id FK INT enrolled_at DATE completed_at DATE score INT job_offers id PK INT student_id FK INT company TEXT role TEXT city TEXT salary_usd INT remote BOOLEAN offer_date DATE

How the tables join

Relationship Cardinality Join condition
students.cohort_id → cohorts.id many students → one cohort JOIN cohorts ON students.cohort_id = cohorts.id
enrollments.student_id → students.id many enrollments → one student JOIN students ON enrollments.student_id = students.id
enrollments.course_id → courses.id many enrollments → one course JOIN courses ON enrollments.course_id = courses.id
job_offers.student_id → students.id many job offers → one student JOIN students ON job_offers.student_id = students.id

In short: each student belongs to one cohort. Students enroll in courses through enrollments, and their job offers land in job_offers.

SQL’s regex operator ~ becomes the Column method .rlike() (“regex like”).

SELECT name FROM students WHERE name ~ '^[AM]';
students.filter(col("name").rlike("^[AM]")).select("name")

The same regex syntax

Everything you learned in the SQL regex topic carries over unchanged:

PatternMatches
.any single character
^ / $start / end of the string
[abc], [a-z], [0-9]character sets and ranges
+ / * / ?one or more / zero or more / optional
(ab|cd)ab or cd
courses.filter(col("title").rlike("[0-9]"))                  # contains a digit
job_offers.filter(col("role").rlike("(Analyst|Engineer)"))   # either word
students.filter(col("name").rlike("^A.*a$"))                 # starts A, ends a

Like in SQL, an unanchored regex matches anywhere in the string — use ^ and $ to pin it down.

Cleaning data with regex

The matching operator’s best friend is the replacement function — a data engineering workhorse:

students.select(F.regexp_replace(col("name"), "[aeiou]", "*").alias("masked"))

You will use regexp_replace for stripping currency signs, fixing phone formats, and normalizing messy text in almost every pipeline.

When to use what

  • Exact value → ==
  • Starts with / contains / ends with → like(), startswith(), contains()
  • Anything more complex → rlike()

Practice

Real Python runs in your browser with the PySpark DataFrame API. Solve the tasks, or just experiment.