Logo
Published on

Regex for Switch Case in TypeScript

Introduction

Regular expressions (regex) are powerful tools for pattern matching and text manipulation. When combined with TypeScript's switch case statements, they can create flexible and efficient code for string processing tasks.

Developers often struggle with complex string parsing scenarios. By using regex in switch cases, you can simplify (or maybe not) your code and handle various string patterns more elegantly.

Understanding Regex in TypeScript

Basic Regex Syntax

Regular expressions in TypeScript use the same syntax as JavaScript. Here's a quick refresher on some common regex patterns:

  • ^: Start of the string
  • $: End of the string
  • \d: Any digit
  • \w: Any word character (letter, digit, or underscore)
  • *: Zero or more occurrences
  • +: One or more occurrences

Creating Regex Objects

In TypeScript, you can create regex objects in two ways:

  1. Using the RegExp constructor:
const pattern = new RegExp('^hello')
  1. Using regex literals:
const pattern = /^hello/

Implementing Regex in Switch Cases

Basic Switch Case with Regex

Let's start with a simple example of using regex in a switch case:

function processInput(input: string): string {
  switch (true) {
    case /^\d+$/.test(input):
      return 'Input is a number'
    case /^[A-Za-z]+$/.test(input):
      return 'Input is a word'
    default:
      return 'Input is neither a number nor a word'
  }
}

console.log(processInput('123')) // Output: Input is a number
console.log(processInput('hello')) // Output: Input is a word
console.log(processInput('123abc')) // Output: Input is neither a number nor a word

Advanced Regex Patterns

You can use more complex regex patterns to handle various scenarios:

function categorizeEmail(email: string): string {
  switch (true) {
    case /^[a-zA-Z0-9._%+-]+@gmail\.com$/.test(email):
      return 'Gmail account'
    case /^[a-zA-Z0-9._%+-]+@outlook\.com$/.test(email):
      return 'Outlook account'
    case /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email):
      return 'Other email provider'
    default:
      return 'Invalid email format'
  }
}

console.log(categorizeEmail('[email protected]')) // Output: Gmail account
console.log(categorizeEmail('[email protected]')) // Output: Outlook account
console.log(categorizeEmail('[email protected]')) // Output: Other email provider
console.log(categorizeEmail('invalid-email')) // Output: Invalid email format

Best Practices and Tips

Performance Considerations

When using regex in switch cases, keep these performance tips in mind:

  1. Compile regex patterns outside the switch statement if they're used repeatedly.

  2. Use non-capturing groups (?:...) instead of capturing groups (...) when you don't need to extract matched content.

Maintainability

To improve code maintainability:

  1. Use constants for regex patterns to improve readability.
  2. Add comments explaining complex regex patterns.
  3. Use tools like Regex101 to visualize regex patterns.

Example:

const NUMBER_PATTERN = /^\d+$/
const WORD_PATTERN = /^[A-Za-z]+$/

function processInput(input: string): string {
  switch (true) {
    case NUMBER_PATTERN.test(input):
      return 'Input is a number'
    case WORD_PATTERN.test(input):
      return 'Input is a word'
    default:
      return 'Input is neither a number nor a word'
  }
}

Conclusion

Remember, like any powerful tool, use this technique wisely. While it's tempting to create elaborate regex patterns, sometimes simpler is better. Start small, test thoroughly, and gradually build up to more complex patterns as needed.