How to use Regular Expression In Javascript

Using regular expression to find strings matching a pattern involves creating a regex pattern from the input pattern, replacing ‘?’ with ‘.’ to match any character, then filtering the dictionary based on regex matches.

Example:

JavaScript
function findMatchingStrings(dictionary, pattern) {
  const regex = new RegExp(`^${pattern.replace(/\?/g, '.')}$`);
  return dictionary.filter(word => regex.test(word));
}


const dictionary = ["cat", "bat", "rat", "hat", "mat"];
const pattern = "b?t";
const matchingStrings = findMatchingStrings(dictionary, pattern);
console.log(matchingStrings); // Output: ["bat"]

Output
[ 'bat' ]




JavaScript Program to Find all Strings that Match Specific Pattern in a Dictionary

Finding all strings in a dictionary that match a specific pattern in JavaScript involves searching for words that follow a particular structure or format within a given dictionary. The pattern can include placeholders for characters, allowing flexibility in the search. In this article, we will explore various approaches for finding all strings that match specific patterns in a dictionary in JavaScript.

Examples:

Input: words= ["sss", "mmm", "tyu", "abc"];
            pattern = "aaa"
Output: ["sss" "mmm"]
Explanation: sss and mmm have,similar pattern.
Input: words = ["123", "112", "456", "133"];
            pattern = "mno"
Output: ["123" "456"]
Explanation: 123 and 456 have,similar pattern.

Similar Reads

Method 1: Naive Approach

The objective is to determine if a word shares the same structural pattern as the given pattern. One way to tackle this challenge is by creating a unique numerical representation for both the word and the pattern and then checking if they match. To put it simply, we assign distinct numerical values to the individual characters within the word, creating a sequence of integers (referred to as the word’s hash) based on the frequency of each character. Subsequently, we compare this hash with the pattern’s hash to establish if they are identical....

Method 2: Efficient approach

We directly associate the pattern’s letters with the corresponding letters in the word. When processing the current character, if it hasn’t been mapped yet, we map it to the corresponding character in the word. If it’s already mapped, we verify if the previous mapping matches the current character in the word....

Method 3: Using Regular Expression

Using regular expression to find strings matching a pattern involves creating a regex pattern from the input pattern, replacing ‘?’ with ‘.’ to match any character, then filtering the dictionary based on regex matches....