String matching where one string contains wildcard characters

22 Jun, 2022
Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. 
* --> Matches with 0 or more instances of any character or set of characters.
? --> Matches with any one character.
For example, “g*ks” matches with “geeks” match. And string “ge?ks*” matches with “geeksforgeeks” (note ‘*’ at the end of first string). But “g*k” doesn’t match with “gee” as character ‘k’ is not present in second string. 
C++
Java
Python3
C#
Javascript
// A C program to match wild card characters#include <stdbool.h>#include <stdio.h> // The main function that checks if two given strings// match. The first string may contain wildcard charactersbool match(char* first, char* second){    // If we reach at the end of both strings, we are done    if (*first == '\0' && *second == '\0')        return true;     // Make sure to eliminate consecutive '*'    if (*first == '*') {        while (*(first + 1) == '*')            first++;    }     // Make sure that the characters after '*' are present    // in second string. This function assumes that the    // first string will not contain two consecutive '*'    if (*first == '*' && *(first + 1) != '\0'        && *second == '\0')        return false;     // If the first string contains '?', or current    // characters of both strings match    if (*first == '?' || *first == *second)        return match(first + 1, second + 1);     // If there is *, then there are two possibilities    // a) We consider current character of second string    // b) We ignore current character of second string.    if (*first == '*')        return match(first + 1, second)               || match(first, second + 1);    return false;} // A function to run test casesvoid test(char* first, char* second){    match(first, second) ? puts("Yes") : puts("No");} // Driver program to test above functionsint main(){    test("g*ks", "geeks"); // Yes    test("ge?ks*", "geeksforgeeks"); // Yes    test("g*k", "gee"); // No because 'k' is not in second    test("*pqrs",         "pqrst"); // No because 't' is not in first    test("abc*bcd", "abcdhghgbcd"); // Yes    test("abc*c?d", "abcd"); // No because second must have                             // 2 instances of 'c'    test("*c*d", "abcd"); // Yes    test("*?c*d", "abcd"); // Yes    test("geeks**", "geeks"); // Yes     return 0;}
// Java program to match wild card charactersclass GFG{ // The main function that checks if// two given strings match. The first string// may contain wildcard charactersstatic boolean match(String first, String second){     // If we reach at the end of both strings,    // we are done    if (first.length() == 0 && second.length() == 0)        return true;     // Make sure to eliminate consecutive '*'    if (first.length() > 1 &&first.charAt(0) == '*') {      int i=0;        while (i+1<first.length() && first.charAt(i+1) == '*')          i++;      first=first.substring(i);    }     // Make sure that the characters after '*'    // are present in second string.    // This function assumes that the first    // string will not contain two consecutive '*'    if (first.length() > 1 && first.charAt(0) == '*' &&                              second.length() == 0)        return false;     // If the first string contains '?',    // or current characters of both strings match    if ((first.length() > 1 && first.charAt(0) == '?') ||        (first.length() != 0 && second.length() != 0 &&         first.charAt(0) == second.charAt(0)))        return match(first.substring(1),                     second.substring(1));     // If there is *, then there are two possibilities    // a) We consider current character of second string    // b) We ignore current character of second string.    if (first.length() > 0 && first.charAt(0) == '*')        return match(first.substring(1), second) ||               match(first, second.substring(1));    return false;} // A function to run test casesstatic void test(String first, String second){    if (match(first, second))        System.out.println("Yes");    else        System.out.println("No");} // Driver Codepublic static void main(String[] args){    test("g*ks", "geeks"); // Yes    test("ge?ks*", "geeksforgeeks"); // Yes    test("g*k", "gee"); // No because 'k' is not in second    test("*pqrs", "pqrst"); // No because 't' is not in first    test("abc*bcd", "abcdhghgbcd"); // Yes    test("abc*c?d", "abcd"); // No because second must have 2                            // instances of 'c'    test("*c*d", "abcd"); // Yes    test("*?c*d", "abcd"); // Yes      test("geeks**", "geeks"); // Yes}} // This code is contributed by// sanjeev2552
# Python program to match wild card characters # The main function that checks if two given strings match.# The first string may contain wildcard characters  def match(first, second):     # If we reach at the end of both strings, we are done    if len(first) == 0 and len(second) == 0:        return True     # Make sure to eliminate consecutive '*'    if len(first) > 1 and first[0] == '*':        i = 0        while i+1 < len(first) and first[i+1] == '*':            i = i+1        first = first[i:]     # Make sure that the characters after '*' are present    # in second string. This function assumes that the first    # string will not contain two consecutive '*'    if len(first) > 1 and first[0] == '*' and len(second) == 0:        return False     # If the first string contains '?', or current characters    # of both strings match    if (len(first) > 1 and first[0] == '?') or (len(first) != 0                                                and len(second) != 0 and first[0] == second[0]):        return match(first[1:], second[1:])     # If there is *, then there are two possibilities    # a) We consider current character of second string    # b) We ignore current character of second string.    if len(first) != 0 and first[0] == '*':        return match(first[1:], second) or match(first, second[1:])     return False # A function to run test cases  def test(first, second):    if match(first, second):        print("Yes")    else:        print("No")  # Driver programtest("g*ks", "geeks")  # Yestest("ge?ks*", "geeksforgeeks")  # Yestest("g*k", "gee")  # No because 'k' is not in secondtest("*pqrs", "pqrst")  # No because 't' is not in firsttest("abc*bcd", "abcdhghgbcd")  # Yestest("abc*c?d", "abcd")  # No because second must have 2 instances of 'c'test("*c*d", "abcd")  # Yestest("*?c*d", "abcd")  # Yestest("geeks**", "geeks")  # Yes # This code is contributed by BHAVYA JAIN and ROHIT SIKKA
// C# program to match wild card charactersusing System; class GFG {     // The main function that checks if    // two given strings match. The first string    // may contain wildcard characters    static bool match(String first, String second)    {         // If we reach at the end of both strings,        // we are done        if (first.Length == 0 && second.Length == 0)            return true;         // Make sure to eliminate consecutive '*'        if (first.Length > 1 && first[0] == '*') {            int i = 0;            while (i + 1 < first.Length                   && first[i + 1] == '*')                i++;            first = first.Substring(i);        }         // Make sure that the characters after '*'        // are present in second string.        // This function assumes that the first        // string will not contain two consecutive '*'        if (first.Length > 1 && first[0] == '*'            && second.Length == 0)            return false;         // If the first string contains '?',        // or current characters of both strings match        if ((first.Length > 1 && first[0] == '?')            || (first.Length != 0 && second.Length != 0                && first[0] == second[0]))            return match(first.Substring(1),                         second.Substring(1));         // If there is *, then there are two possibilities        // a) We consider current character of second string        // b) We ignore current character of second string.        if (first.Length > 0 && first[0] == '*')            return match(first.Substring(1), second)                || match(first, second.Substring(1));        return false;    }     // A function to run test cases    static void test(String first, String second)    {        if (match(first, second))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }     // Driver Code    public static void Main(String[] args)    {        test("g*ks", "geeks"); // Yes        test("ge?ks*", "geeksforgeeks"); // Yes        test("g*k",             "gee"); // No because 'k' is not in second        test("*pqrs",             "pqrst"); // No because 't' is not in first        test("abc*bcd", "abcdhghgbcd"); // Yes        test("abc*c?d", "abcd"); // No because second must                                 // have 2 instances of 'c'        test("*c*d", "abcd"); // Yes        test("*?c*d", "abcd"); // Yes        test("geeks**", "geeks"); // Yes    }} // This code is contributed by Rajput-Ji
<script> // Javascript program to match wild card characters // The main function that checks if// two given strings match. The first string// may contain wildcard charactersfunction match(first, second){     // If we reach at the end of both strings,    // we are done    if (first.length == 0 && second.length == 0)        return true;     // Make sure that the characters after '*'    // are present in second string.    // This function assumes that the first    // string will not contain two consecutive '*'    if (first.length > 1 && first[0] == '*' &&        second.length == 0)        return false;     // If the first string contains '?',    // or current characters of both strings match    if ((first.length > 1 && first[0] == '?') ||        (first.length != 0 && second.length != 0 &&         first[0] == second[0]))        return match(first.substring(1),                     second.substring(1));     // If there is *, then there are two possibilities    // a) We consider current character of second string    // b) We ignore current character of second string.    if (first.length > 0 && first[0] == '*')        return match(first.substring(1), second) ||               match(first, second.substring(1));                    return false;} // A function to run test casesfunction test(first, second){    if (match(first, second))       document.write("Yes" + "<br>");    else       document.write("No" + "<br>");} // Driver codeass="plain">test("g*ks", "geeks"); // Yestest("ge?ks*", "geeksforgeeks"); // Yestest("g*k", "gee"); // No because 'k' is not in secondtest("*pqrs", "pqrst"); // No because 't' is not in firsttest("abc*bcd", "abcdhghgbcd"); // Yestest("abc*c?d", "abcd"); // No because second must have 2                        // instances of 'c'test("*c*d", "abcd"); // Yestest("*?c*d", "abcd"); // Yes // This code is contributed by SoumikMondal </script>
Output: 
Yes
Yes
No
No
Yes
No
Yes
Yes
Yes
Time Complexity: O(n)
Auxiliary Space: O(1)
String matching where one string contains wildcard characters | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersString matching where one string contains wildcard characters | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Q6ZX95GadA8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Exercise 1) In the above solution, all non-wild characters of first string must be there is second string and all characters of second string must match with either a normal character or wildcard character of first string. Extend the above solution to work like other pattern searching solutions where the first string is pattern and second string is text and we should print all occurrences of first string in second. 2) Write a pattern searching function where the meaning of ‘?’ is same, but ‘*’ means 0 or more occurrences of the character just before ‘*’. For example, if first string is ‘a*b’, then it matches with ‘aaab’, but doesn’t match with ‘abb’. This article is compiled by Vishal Chaudhary and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
sanjeev2552
Rajput-Ji
SoumikMondal
amartyaghoshgfg
dheerukd2002
akashish__
Amazon
Ola Cabs
Pattern Searching
Strings
Amazon
Ola Cabs
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.