Natural Language Processing · Beginner level

Beginner level · Module 3: Text Cleaning and Preprocessing · Lesson 2 of 3

Regular Expressions for Text Patterns

An introduction to regular expressions for finding and replacing patterns such as phone numbers, dates, amounts and repeated punctuation, with the Python re module.

In this lesson you will

  • Write simple regular expressions
  • Use re.sub and re.findall to clean and extract patterns

Key concepts

regular expressioncharacter classes (\d, \w, \s)quantifiersre.subre.findall

The lesson

A regular expression (regex) describes a text pattern. \d matches a digit, \w a letter, digit or underscore, \s a space, + means 'one or more' and {3} means 'exactly three'. \b marks a word boundary.

re.sub(pattern, replacement, text) replaces every match. re.findall(pattern, text) returns every match as a list. Together they can mask phone numbers, remove repeated exclamation marks or pull out amounts such as '25,000 SSP'.

Regexes are powerful but easy to get wrong. Always test a new pattern on examples that should match and examples that should not, and keep patterns simple enough that a colleague can read them.

Step by step

  1. Write a pattern for local mobile numbers written as 0912 345 678 or 0912-345-678.
  2. Test it with re.findall on ten sample strings, including ones that should not match.
  3. Replace matches with '<PHONE>' using re.sub.
  4. Write a pattern that reduces '!!!' to '!'.
Code example

Cleaning, masking and tokenising a school-fees message

Lowercasing, a regular expression that masks a phone number, regex tokenisation and stop-word removal applied step by step to one realistic SMS.

Pythonpreprocess_message.py
import re message = ("Hello, I paid the school fees on 3 March but my receipt still shows "           "UNPAID!!! Please help. Tel 0912 345 678")   # synthetic message text = message.lower()# Mask local mobile numbers written as 0912 345 678 or 0912-345-678text = re.sub(r"\b0\d{3}[\s-]?\d{3}[\s-]?\d{3}\b", "<PHONE>", text) # Tokens: the phone placeholder, words, or numbers (punctuation is dropped)tokens = re.findall(r"<PHONE>|[a-z]+|\d+", text) # A small task-specific stop list; 'not' and 'no' are deliberately kept out of itstop_words = {"hello", "i", "the", "on", "but", "my", "still", "please", "tel"}content = [t for t in tokens if t not in stop_words] print(text)print(len(tokens), tokens)print(len(content), content)

Output

hello, i paid the school fees on 3 march but my receipt still shows unpaid!!! please help. tel <PHONE>
19 ['hello', 'i', 'paid', 'the', 'school', 'fees', 'on', '3', 'march', 'but', 'my', 'receipt', 'still', 'shows', 'unpaid', 'please', 'help', 'tel', '<PHONE>']
10 ['paid', 'school', 'fees', '3', 'march', 'receipt', 'shows', 'unpaid', 'help', '<PHONE>']

How it works

Lowercasing makes 'UNPAID' and 'unpaid' the same token. The regular expression \b0\d{3}[\s-]?\d{3}[\s-]?\d{3}\b matches a 0 followed by three digits, then two groups of three digits separated by an optional space or hyphen, so the phone number is replaced by <PHONE> before anything else sees it. This protects privacy and stops a model learning from individual numbers. re.findall keeps the placeholder, words and numbers and drops punctuation, giving 19 tokens. Removing a task-specific stop list leaves 10 content tokens that carry the meaning: a fees payment, a date and an unpaid receipt. Note the choices: '3' and 'march' are kept because dates matter for fees enquiries, and negations would be kept because 'not paid' and 'paid' mean opposite things. The '!!!' is lost here; for sentiment analysis you might keep it.

Key concepts

lowercasingre.sub maskingre.findall tokenisationtask-specific stop wordsinformation kept vs lost

Practice activity

Build a regex-based masking step for phone numbers and email addresses and test it on 20 sample messages.

Expected result: Patterns that mask every phone number and email in the samples without changing other text.

Check your understanding

  1. What does \d{3} match?

    Show answer

    Exactly three digits.

  2. Why test a regex on examples that should not match?

    Show answer

    To make sure it does not change text it should leave alone.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.