Wildcard Pattern Matching in JavaScript
Last Updated :
26 Sep, 2023
In this article, we will see Pattern matching with wildcards which is an encountered problem, in the field of computer science and string manipulation. The objective is to determine whether a given wildcard pattern matches a string or not. In this article, we will discuss the step-by-step algorithm for wildcard pattern matching providing code examples in JavaScript.
Understanding Wildcard Patterns
A wildcard pattern consists of letters as special symbols like
- ‘*’ which represents a sequence of characters (including an empty space)
- ‘?’ which represents a single character.
Example:
Text = "GeeksforGeeks",
Pattern = “*****Ge*****ks", output: true
Pattern = "Geeksfor?eeks", output: true
Pattern = "Ge*k?", output: true
Pattern = "e*ks", output: false
Approaches for Wildcard Pattern Matching
- Javascript Regular Expression
- Pattern-Matching Algorithm
JavaScript offers support, for expressions, which provides a convenient way to handle wildcard pattern matching. Regular expressions are patterns that are used to find character combinations within strings.
Here is an example of how you can utilize expressions in JavaScript to perform pattern matching:
Syntax:
function wildcardMatch(text, pattern) {
const regexPattern =
new RegExp('^' + pattern.replace(/\?/g, '.').replace(/\*/g, '.*') + '$');
return regexPattern.test(text);
}
Parameters:
- text: It is the main string that is to be checked.
- pattern: It is the wildcard pattern that is used to check the specific pattern in the text.
In this implementation:
- The wildcardMatchRegExp function converts the given wildcard pattern into a regular expression pattern. It replaces ‘?’ with ‘.’ to match any character. With ‘.’ to match zero or more characters.
- To ensure that the entire string matches the pattern the regular expression is anchored at the start (^). End ($) of the string.
- The test method of the regular expression object is used to check if the text matches the pattern.
This approach is concise. Leverages JavaScripts built-in functionality, for expressions enabling efficient handling of wildcard pattern matching. Similarly, you can add test cases by providing text and pattern values and verifying their results.
Example: This example demonstrates the above-mentioned approach.
Javascript
function wildcardMatchRegExp(text, pattern) {
const regexPattern = new RegExp(
"^" +
pattern
.replace(/\?/g, "." )
.replace(/\*/g, ".*" ) +
"$"
);
return regexPattern.test(text);
}
const text = "GeeksforGeeks" ;
const pattern = "*****Ge****ks" ;
if (wildcardMatchRegExp(text, pattern)) {
console.log( "Pattern is Matched" );
} else {
console.log( "Pattern is not matched" );
}
|
Output
Pattern is Matched
Wildcard Pattern Matching using Pattern-Matching Algorithm
The algorithm deals with symbols, in the pattern like ‘*’ which matches sequences of characters ( empty ones), and ‘?’, which matches just one character.
Algorithm Steps:
Let’s break down the steps involved in the pattern-matching algorithm:
- Calculate the length of both the text (n) and the pattern (m).
- If any of the patterns is an empty string i.e. n==0 or m == 0. then return false.
- Use a JavaScript loop with two pointers i and j, to iterate both the string and apply matching.
- Increase both i and j by 1 when:
- character at text[i] and pattern[j] are same.
- pattern[j] is a symbol ‘?’.
- Store the values of i and j as textPointer and pattPointer if j encounters the ‘*’ symbol and increament j to move past the ‘*’ symbols
- If the pattpointer is updated increment i, j, textPointer by 1.
- Iterate while j is within bounds and pattern[j] is a ‘*’ symbol, increment j to move past the ‘*’.
- If the j pointer reaches the end of the pattern i.e. j == m return true else return false.
Example: Below is the implementation of the above algorithm in JavaScript.
Javascript
function wildcard(text, pattern) {
const n = text.length;
const m = pattern.length;
if (m === 0) {
return n === 0;
}
let i = 0,
j = 0,
textPointer = -1,
pattPointer = -1;
while (i < n) {
if (text[i] === pattern[j]) {
i++;
j++;
} else if (j < m && pattern[j] === "?" ) {
i++;
j++;
} else if (j < m && pattern[j] === "*" ) {
textPointer = i;
pattPointer = j;
j++;
} else if (pattPointer !== -1) {
j = pattPointer + 1;
i = textPointer + 1;
textPointer++;
} else {
return false ;
}
}
while (j < m && pattern[j] === "*" ) {
j++;
}
return j === m;
}
const text = "GeeksforGeeks" ;
const pattern = "*****Ge****ks" ;
if (wildcard(text, pattern)) {
console.log( "Pattern is Matched" );
} else {
console.log( "Pattern is not Matched" );
}
|
Output
Pattern is Matched
Time Complexity: O(n*m) where “n” is the length of the text string, and “m” is the length of the pattern string.
Space Complexity: O(n+m) where “n” is the length of the text string, and “m” is the length of the pattern string.
Similar Reads
Pattern Matching In TypeScript
Pattern matching refers to the ability to check a value against a pattern and execute code based on the matching result, although TypeScript lacks native pattern matching we can implement similar functionality using control flow constructs like switch, type guards, and destructuring. This allows Typ
5 min read
Replacing spaces with underscores in JavaScript
Given a sentence and the task is to replace the spaces(" ") from the sentence with underscores("_") in JavaScript. There are some JavaScript methods are used to replace spaces with underscores which are listed below: JavaScript replace() method: This method searches a string for a defined value, or
2 min read
Replace Multiple Words with K in JavaScript
Sometimes, while working with Javascript strings, we may face a problem in which we have to perform a replacement of multiple words with a single word. This can have applications in many domains like day-day programming and school programming. These are the following approaches:Table of Content Usin
5 min read
JavaScript Symbol match Property
JavaScript Symbol match property is used to identify the matching of a regular expression against a string and this function is called using String match() method. Syntax: regexp[Symbol.match] = false; Parameters: It does not accept any parameters. Return value: It will return the Boolean value for
1 min read
JavaScript String match() Method
The match() method in JavaScript is used for identifying and retrieving substrings that fit a specified pattern, defined by a regular expression. It is often used when you need to find particular patterns within strings, enabling efficient text processing. This method returns an array of matched sub
3 min read
JavaScript RegExp \d Metacharacter
In JavaScript regular expressions, the \d metacharacter is used to match any digit character (0-9). This is a shorthand for the character class [0-9], which matches any single character within the specified range. To begin, let's look at a simple example where we use \d to match digits in a string.
3 min read
JavaScript RegExp \D Metacharacter
The RegExp \D Metacharacter in JavaScript is used to search non-digit characters i.e all the characters except digits. It is the same as [^0-9]. [GFGTABS] JavaScript let str = "a1234g5g5"; let regex = /\D/g; let match = str.match(regex); console.log("Found " + match.length +
1 min read
JavaScript RegExp \B Metacharacter
The \B metacharacter in JavaScript regular expressions matches a position where a word boundary does not exist. It is essentially the opposite of the \b (word boundary) metacharacter. [GFGTABS] JavaScript let regex = /\Bcat\B/; let str1 = "concat"; let str2 = "cat"; console.log(r
2 min read
JavaScript RegExp \b Metacharacter
The \b metacharacter in JavaScript regular expressions represents a word boundary, allowing you to match positions where a word begins or ends. A word boundary is the position between a word character (\w: letters, digits, or underscores) and a non-word character (\W: everything else, including spac
3 min read
JavaScript - String Strip
Here are the different methods to Strip String in JavaScript Using trim() Method (Most Common)The trim() method removes whitespace from both ends of a string. This is the most commonly used to strip whitespace in JavaScript. [GFGTABS] JavaScript const s1 = " Hello, World! "; const s2 = s1.
2 min read