Regular Expression Matching

JavaScript

Regular Expression

Regular expressions, often abbreviated as "regex" or "regexp," are powerful tools for pattern matching and manipulation of text in JavaScript. They provide a concise and flexible means of searching, replacing, and validating strings.

Implement regular expression matching with support for '.' and '*':

Here's a simple implementation of regular expression matching in JavaScript with support for '.' (matching any single character) and '*' (matching zero or more occurrences of the preceding element):

js Copy Code
function isMatch(s, p) {
    if (p.length === 0) {
        return s.length === 0;
    }

    // Check if the first characters match
    let firstMatch = s.length > 0 && (s[0] === p[0] || p[0] === '.');

    // Case when the pattern has '*'
    if (p.length >= 2 && p[1] === '*') {
        // Recursive call without the '*' case and skipping the current character
        return (
            isMatch(s, p.slice(2)) || // zero occurrence
            (firstMatch && isMatch(s.slice(1), p)) // one or more occurrences
        );
    } else {
        // No '*' case
        return firstMatch && isMatch(s.slice(1), p.slice(1));
    }
}

// Example usage:
console.log(isMatch("aa", "a")); // false
console.log(isMatch("aa", "a*")); // true
console.log(isMatch("ab", ".*")); // true
console.log(isMatch("aab", "c*a*b")); // true
Output:
false
true
true
true

Explanation:

This implementation works recursively, trying to match characters one by one while considering the special cases for '.' and '*'. Note that this implementation may not be the most efficient for large inputs, but it gives a basic understanding of how regular expression matching works.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.