Regular Expressions and Globbing Guide

Prepared by: Anwer Sadath Abdul Muttaliff

Introduction

This guide provides a practical overview of regular expressions (regex) and globbing. Learn the essentials, practice with exercises, and check solutions to enhance your skills.

Regex Basics

Parentheses () - Grouping and Capturing

Grouping: Used to group parts of a pattern. Example: (abc)* matches abc, abcabc, etc.

Capturing: Stores matched text for later use. Example: (abc)(def) matches abcdef and captures abc and def.

Braces {} - Quantifiers

Exact Number: {3} matches exactly three occurrences. Example: a{3} matches aaa.

Range: {2,4} matches 2 to 4 occurrences. Example: a{2,4} matches aa, aaa, aaaa.

Square Brackets [] - Character Classes

Any One Character: [abc] matches a, b, or c.

Negation: [^abc] matches any character except a, b, or c.

Globbing Basics

Globbing expands wildcard patterns into matching filenames in shell commands like ls, cp, and mv.

Practical Exercises

Create a file named regex_test.txt with the following content:

user123@example.com
admin456@example.com
support789@example.net
hello@example.org
test01@gmail.com
info@company.com
contact@service.net
sales@business.org
error404@domain.com
user@testsite.com
123-456-7890
987-654-3210
(123) 456-7890
(987) 654-3210
01-2345-6789
12-3456-7890
abc_def@example.com
john.doe@example.com
123example.com
invalid.email@com
192.168.1.1
255.255.255.255
#1A2B3C
#FF0000
#00FF00
2023-05-15
1999-12-31
2030-01-01
http://www.example.com
https://example.net
https://www.example.org
00:1A:2B:3C:4D:5E
01:23:45:67:89:AB
AB:CD:EF:12:34:56

Exercises

1. Match Exactly Three Digits
egrep "[0-9]{3}" regex_test.txt
2. Match Email Addresses
egrep "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" regex_test.txt
3. Match Phone Numbers
egrep "\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}" regex_test.txt
4. Match Valid IPv4 Addresses
egrep "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" regex_test.txt
5. Match Hexadecimal Color Codes
egrep "#[A-Fa-f0-9]{6}" regex_test.txt
6. Match Valid Dates (YYYY-MM-DD)
egrep "^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$" regex_test.txt
7. Match Valid URLs
egrep "https?://([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})" regex_test.txt
8. Match Valid MAC Addresses
egrep "^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$" regex_test.txt

Solutions

All solutions are provided within the exercises above. Use the egrep commands to test your regex patterns.

Back to Top Back to Home