69 – Pattern matching (Javascript)

Exploring Regular Expressions: Pattern Matching in JavaScript

Regular expressions, often referred to as “regex” or “regexp,” are a powerful tool for pattern matching and text manipulation in JavaScript. They provide a concise and flexible way to search, extract, and replace text based on specific patterns. In this guide, we’ll dive into the world of regular expressions, understanding their syntax and exploring practical examples of pattern matching in JavaScript.

What Are Regular Expressions?

Regular expressions are patterns used to match character combinations in strings. They are a domain-specific language for specifying text patterns. In JavaScript, regular expressions are defined using the RegExp object or a literal notation.

Creating a Regular Expression

In JavaScript, you can create a regular expression using the RegExp constructor or a literal notation enclosed in forward slashes. For example:

JavaScript:


// Using the constructor
const pattern1 = new RegExp('abc');

// Using the literal notation
const pattern2 = /abc/;

The patterns pattern1 and pattern2 both match the characters “abc” in a string.

Basic Pattern Matching

Let’s explore some common patterns and their usage in JavaScript:

1. Matching Literal Text

To match a specific sequence of characters, use that sequence in your regular expression. For example:

JavaScript:


const pattern = /apple/;
const text = 'I have an apple and a banana.';

if (pattern.test(text)) {
  console.log('Found: apple');
} else {
  console.log('Not found: apple');
}
2. Character Classes

You can use character classes to match any character from a defined set. For example, [aeiou] matches any vowel:

JavaScript:


const pattern = /[aeiou]/;
const text = 'Regular expressions are awesome!';

const matches = text.match(pattern);
console.log(matches); // ['e', 'u', 'a', 'e', 'i', 'o', 'a', 'e', 'o', 'e']
3. Quantifiers

Quantifiers specify how many times the preceding character or group should appear. For example, \d{3} matches three consecutive digits:

JavaScript:


const pattern = /\d{3}/;
const text = 'The PIN is 12345.';

const match = text.match(pattern);
console.log(match); // ['123']
4. Anchors

Anchors define where the pattern should appear in the text. ^ matches the start of a string, and $ matches the end. For example:

JavaScript:


const pattern = /^apple$/;
const text = 'apple';

if (pattern.test(text)) {
  console.log('Matched: apple');
} else {
  console.log('No match');
}
5. Alternation

Use the | (pipe) symbol to specify alternatives. For example, cat|dog matches either “cat” or “dog”:

JavaScript:


const pattern = /cat|dog/;
const text = 'I have a cat and a dog.';

const matches = text.match(pattern);
console.log(matches); // ['cat', 'dog']
Advanced Pattern Matching

Regular expressions offer more advanced features like capturing groups, lookahead and lookbehind assertions, and flags for case insensitivity and global matching. These features make regex incredibly powerful for text processing tasks.

Practical Example: Validating Email Addresses

Let’s explore a practical example where we validate email addresses using a regular expression:

JavaScript:


const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
const email = 'user@example.com';

if (emailPattern.test(email)) {
  console.log('Valid email address');
} else {
  console.log('Invalid email address');
}

In this example, the regular expression emailPattern checks if the email address matches the common email format.

Conclusion

Regular expressions are a powerful tool in JavaScript for pattern matching and text manipulation. They can be used for simple tasks like searching for a specific word or complex tasks like validating email addresses. Understanding regular expressions is essential for developers who need to work with text data effectively.