Natural Language Processing (NLP)
Instructor: Waqas Ahmed (Khilji Khan)
PhD (Scholar)…
[Link]
Module 2: RegExpression Using Python
• Basics of RegExpression
A1. Basics of Regular Expressions (Theory)
Answer the following questions briefly: 1. What is a Regular Expression (Regex)? Why is it
important in text processing? 2. Explain the following Regex components with examples: -
Literals - Metacharacters (. ^ $ * + ? { } [ ] | ( )) - Character classes - Quantifiers -
Anchors - Groups and capturing 3. Difference between [Link](), [Link](), [Link](), and [Link]().
A2. Practical Tasks (Python)
Write Python programs using the re module to: 1. Extract all email addresses from a given
text file. 2. Validate a Pakistani mobile number format. 3. Find and replace all dates in the
format DD/MM/YYYY with YYYY-MM-DD. 4. Tokenize a paragraph into words using Regex
(without NLTK).
1. Introduction
A Regular Expression (RegEx) is a special string pattern used to search, match, extract, or replace text.
Think of it as a pattern-matching language: you tell Python what the text should “look like,” and it finds all strings
that match that pattern.
Why RegEx is important
• Validate user inputs (emails, phone numbers, passwords)
• Extract useful information from text (dates, names, prices)
• Clean and preprocess text for NLP or data analysis
• Search and replace in large text files automatically
2. Python re Module
Python provides the re module to work with RegEx.
import re
Key Functions
Function Purpose Example
[Link]() Matches pattern only at the start of a string [Link](r'Hello', 'Hello world') → match
Searches for first occurrence anywhere in
[Link]() [Link](r'world', 'Hello world') → match
string
[Link](r'\d+', 'I have 2 apples and 10 oranges') →
[Link]() Returns all matches as a list
['2','10']
Function Purpose Example
Returns an iterator of match objects for all
[Link]() Useful for positions
matches
[Link]() Splits string using pattern as separator [Link](r'\s+', 'Hello world') → ['Hello','world']
[Link](r'apples','mangoes','I have apples') → 'I have
[Link]() Replaces pattern with a string
mangoes'
3. RegEx Syntax & Symbols
a) Character Types