Practical Applications of Regex

Practical Applications of Regex

Real-World Use Cases

Regular expressions are used in many real-world scenarios for tasks such as data validation, text processing, and data extraction. Let’s explore some practical applications of Regex in web development.

1. Form Validation

Regex is commonly used to validate user input in web forms, such as email addresses, phone numbers, and passwords.

Example: Validating an Email Address

javascript
	const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
	const isValidEmail = emailRegex.test('test@example.com');
	console.log(isValidEmail); // true

Example: Validating a Password

javascript
	const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
	const isValidPassword = passwordRegex.test('Password1');
	console.log(isValidPassword); // true
	
	// Explanation:
	// (?=.*[A-Za-z]) : At least one letter
	// (?=.*\d)       : At least one digit
	// [A-Za-z\d]{8,} : Minimum 8 characters

2. Search and Replace

Regex can be used to search for patterns in a string and replace them with new values.

Example: Replacing Dates

javascript
	const dateStr = "Today's date is 2024-07-13";
	const regexDate = /(\d{4})-(\d{2})-(\d{2})/;
	const newDateStr = dateStr.replace(regexDate, '$3/$2/$1');
	console.log(newDateStr); // "Today's date is 13/07/2024"
	
	// Explanation:
	// (\d{4}) : Captures the year
	// (\d{2}) : Captures the month
	// (\d{2}) : Captures the day
	// "$3/$2/$1" : Rearranges the captured groups

3. Data Extraction

Regex can extract specific parts of a string, such as extracting domain names from URLs.

Example: Extracting Domain Names

javascript
	const url = 'https://www.example.com/path/to/page';
	const domainRegex = /^https?:\/\/(www\.)?([a-zA-Z0-9.-]+)\//;
	const match = url.match(domainRegex);
	const domain = match ? match[2] : null;
	console.log(domain); // "example.com"
	
	// Explanation:
	// ^https?:\/\/   : Matches the protocol (http or https)
	// (www\.)?       : Optionally matches "www."
	// ([a-zA-Z0-9.-]+) : Captures the domain name
	// \/             : Matches the trailing slash

Example Projects and Exercises

  1. Form Validator
    • Create a simple form validator using Regex to validate email addresses, phone numbers, and passwords.
    • Example form fields: Email, Phone Number, Password.
javascript
	const validateForm = (email, phone, password) => {
	  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
	  const phoneRegex = /^\+?\d{1,3}?[-.\s]?\(?\d{1,4}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/;
	  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
	
	  const isEmailValid = emailRegex.test(email);
	  const isPhoneValid = phoneRegex.test(phone);
	  const isPasswordValid = passwordRegex.test(password);
	
	  return isEmailValid && isPhoneValid && isPasswordValid;
	};
	
	console.log(validateForm('test@example.com', '+1-800-555-1234', 'Password1')); // true
	console.log(validateForm('invalid-email', '12345', 'pass')); // false
  1. Text Processor
    • Create a text processor that uses Regex to replace certain patterns, such as converting dates from YYYY-MM-DD to DD/MM/YYYY.
javascript
	const convertDates = (text) => {
	  const dateRegex = /(\d{4})-(\d{2})-(\d{2})/g;
	  return text.replace(dateRegex, '$3/$2/$1');
	};
	
	const text = 'The event is scheduled for 2024-07-13 and 2024-08-25.';
	console.log(convertDates(text)); // "The event is scheduled for 13/07/2024 and 25/08/2024."
  1. URL Extractor
    • Create a script that extracts all URLs from a given text and prints the domain names.
javascript
	const extractDomains = (text) => {
	  const urlRegex = /https?:\/\/(www\.)?([a-zA-Z0-9.-]+)\//g;
	  const matches = text.matchAll(urlRegex);
	  const domains = [...matches].map((match) => match[2]);
	  return domains;
	};
	
	const text = 'Visit https://www.example.com and http://example.org for more info.';
	console.log(extractDomains(text)); // ["example.com", "example.org"]

By applying these practical Regex patterns, you can handle various real-world tasks in web development efficiently.