Practical Examples of Regex in Everyday Coding

Even if you hate to write or test Regular Expressions, this could be a better and optimal solution for your next project and could save a lot of if-else conditions. They enable you to search, match, and manipulate text efficiently. In this article, we'll explore practical examples of regex that you can apply in various scenarios, from validating user input to extracting and transforming data.

If you are not aware or confident about Regular Expressions, I would recommend reading about it here.

Example 1: Validating an Email Address

One of the most common uses of regex is to validate email addresses. Ensuring that an email address has the correct format is crucial for any application that handles user registration or communication.

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Explanation:

  • ^[a-zA-Z0-9._%+-]+: Matches the username part of the email, allowing letters, numbers, and special characters like . or _.
  • @: Matches the literal "@" symbol.
  • [a-zA-Z0-9.-]+: Matches the domain name.
  • \.[a-zA-Z]{2,}$: Ensures that the domain ends with a valid top-level domain (e.g., .com, .org).

Example Usage:

Example 2: Extracting Dates from Text

Imagine you have a block of text, and you need to extract all the dates in the format DD/MM/YYYY.

\b\d{2}/\d{2}/\d{4}\b

Explanation:

  • \b: Word boundary to ensure the date is not part of a larger string.
  • \d{2}: Matches two digits for the day and month.
  • /: Matches the literal "/" character.
  • \d{4}: Matches four digits for the year.

Example Usage:

  • Today is 14/08/2024: Extracts 14/08/2024
  • The event was on 01/01/2023 and 31/12/2023: Extracts 01/01/2023 and 31/12/2023

Example 3: Finding All URLs in a Document

If you need to extract URLs from a document, regex can help identify all HTTP and HTTPS links.

https?:\/\/(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\S*)?

Explanation:

  • https?: Matches http or https.
  • :\/\/: Matches the "://" part of the URL.
  • (www\.)?: Optionally matches "www.".
  • [a-zA-Z0-9.-]+\.[a-zA-Z]{2,}: Matches the domain name and top-level domain.
  • (\S*)?: Optionally matches the rest of the URL.

Example Usage:

  • Visit our site at http://www.example.com: Extracts http://www.example.com
  • Check out https://github.com/user/repo: Extracts https://github.com/user/repo

Example 4: Validating a Phone Number

You might want to ensure that a phone number entered by a user matches a specific format, such as (123) 456-7890.

^\(\d{3}\) \d{3}-\d{4}$

Explanation:

  • ^\(\d{3}\): Matches the area code in parentheses.
  • \d{3}: Matches the next three digits.
  • -: Matches the hyphen.
  • \d{4}$: Matches the last four digits.

Example Usage:

  • (123) 456-7890: Valid
  • 123-456-7890: Invalid

Example 5: Replacing Multiple Whitespaces with a Single Space

When dealing with user input or text formatting, you might need to replace multiple spaces with a single space.

\s{2,}

Replacement:

Replace with a single space " ".

Explanation:

  • \s{2,}: Matches two or more whitespace characters.

Example Usage:

  • This is a test.This is a test.

Example 6: Validating a Password

Ensuring that a password meets certain criteria, such as containing at least one uppercase letter, one lowercase letter, one digit, and one special character, can be done using regex.

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Explanation:

  • ^(?=.*[a-z]): Ensures at least one lowercase letter.
  • (?=.*[A-Z]): Ensures at least one uppercase letter.
  • (?=.*\d): Ensures at least one digit.
  • (?=.*[@$!%*?&]): Ensures at least one special character.
  • [A-Za-z\d@$!%*?&]{8,}$: Ensures the password is at least 8 characters long.

Example Usage:

  • Password123!: Valid
  • password: Invalid
  • PASSWORD123: Invalid

Conclusion

Regex is an incredibly versatile tool that can simplify many text-processing tasks. By understanding and applying these examples, you can improve your ability to handle string manipulation, validation, and extraction tasks more efficiently. Practice with these patterns and adapt them to your specific needs to unlock the full potential of regex in your projects.

Happy coding!

Some Useful links: regex101regexr (my favorite) to test your regex patterns.


Leave a Reply

Your email address will not be published. Required fields are marked *