Common Regex Patterns

 1. Matching Digits:

  • Pattern: \d
  • Description: Matches any single digit (0-9).

2. Matching Words:

  • Pattern: \w+
  • Description: Matches one or more word characters (letters, digits, or underscores).

3. Matching Whitespace:

  • Pattern: \s+
  • Description: Matches one or more whitespace characters (spaces, tabs, line breaks).

4. Matching Alphabetic Characters:

  • Pattern: [A-Za-z]+
  • Description: Matches one or more alphabetic characters (uppercase or lowercase).

5. Matching Non-Alphanumeric Characters:

  • Pattern: [^A-Za-z0-9]+
  • Description: Matches one or more characters that are neither letters nor digits.

6. Matching Email Addresses:

  • Pattern: [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
  • Description: Matches valid email addresses.

7. Matching URLs:

  • Pattern: (https?|ftp):\/\/[^\s/$.?#].[^\s]*
  • Description: Matches URLs, including both HTTP and FTP.

8. Matching Dates (MM/DD/YYYY or YYYY-MM-DD):

  • Pattern: \d{1,4}[-/]\d{1,2}[-/]\d{1,4}
  • Description: Matches dates in formats like "2023-10-22," "10/22/23," or "22-10-2023."

9. Matching Phone Numbers (US Format):

  • Pattern: ^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
  • Description: Matches US phone numbers in various formats, like "(123) 456-7890," "123-456-7890," or "123 456 7890."

10. Matching IP Addresses (IPv4):

  • 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: Matches valid IPv4 addresses.

11. Matching HTML Tags:

  • Pattern: <\s*([a-zA-Z][a-zA-Z0-9]*)\s*[^>]*>
  • Description: Matches HTML tags and captures the tag names.

12. Matching Hexadecimal Color Codes:

  • Pattern: #([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})
  • Description: Matches hexadecimal color codes, both with three and six characters (e.g., "#FFA", "#00FF77").

13. Matching Markdown Headings:

  • Pattern: ^(#{1,6})\s(.*)
  • Description: Matches Markdown headings from level 1 to 6 and captures the heading content.

14. Matching Social Security Numbers (SSN):

  • Pattern: ^\d{3}-\d{2}-\d{4}$
  • Description: Matches Social Security Numbers in the format "123-45-6789."

15. Matching Credit Card Numbers:

  • Pattern: \b\d{4}-?\d{4}-?\d{4}-?\d{4}\b
  • Description: Matches credit card numbers, allowing for optional hyphens in the format "0000-0000-0000-0000."

These common regex patterns can serve as building blocks for a wide range of text processing tasks, including validation, data extraction, and pattern matching. You can modify and combine these patterns to suit your specific requirements and achieve precise results in your regex operations.

No comments:

Post a Comment