1. Email Validation:
- Pattern:
^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$ - Description: This regex pattern validates email addresses by checking if they follow the common structure of an email, including an optional username part, "@" symbol, and a domain name with at least one dot.
2. Phone Number Validation:
- Pattern:
^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$ - Description: This regex pattern validates US phone numbers, allowing for variations in formatting, such as "(123) 456-7890," "123-456-7890," and "123 456 7890."
3. URL Extraction:
- Pattern:
(https?|ftp):\/\/[^\s/$.?#].[^\s]* - Description: This regex extracts URLs from text. It matches both HTTP and FTP URLs that start with "http://", "https://", or "ftp://".
4. Date Detection:
- Pattern:
\b(\d{1,4}([-/]\d{1,2}[-/]\d{1,4})?)\b - Description: This regex identifies dates in various formats, such as "2023-10-22," "10/22/23," or "22-10-2023."
5. HTML Tag Matching:
- Pattern:
<\s*([a-zA-Z][a-zA-Z0-9]*)\s*[^>]*> - Description: This regex pattern matches HTML tags in a text document. It captures the tag names for further processing.
6. Extracting Hashtags from Social Media Posts:
- Pattern:
#(\w+) - Description: This regex captures hashtags from social media posts by finding the "#" symbol followed by one or more word characters.
7. Extracting Key-Value Pairs from JSON Data:
- Pattern:
"(.*?)":\s*"(.*?)"(non-greedy) - Description: This regex captures key-value pairs from JSON data by finding text enclosed in double quotes (keys) followed by a colon and a string value also enclosed in double quotes.
8. Tokenizing Sentences:
- Pattern:
[A-Z][^.!?]*[.!?] - Description: This regex pattern tokenizes sentences in text. It matches text starting with an uppercase letter, followed by any text ending with a sentence-ending punctuation (".", "!", "?").
9. Password Strength Validation:
- Pattern:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$ - Description: This regex checks for strong passwords by ensuring they contain at least one lowercase letter, one uppercase letter, one digit, and one special character, with a minimum length of 8 characters.
10. IP Address Matching:
- Pattern:
\b(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b - Description: This regex matches valid IPv4 addresses. It checks that each octet (0-255) is separated by periods.
These practical examples demonstrate how regex can be used for various tasks, including validation, data extraction, and text processing. Regex patterns can be customized to suit specific requirements and can be a powerful tool for working with textual data.
No comments:
Post a Comment