Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python program to check if two strings match where one string contains wildcard characters

check if two strings match where one string contains wildcard characters

Check if two strings match where one string contains Wildcard Characters

In this page we will learn about how to check if two strings match where one string contains wildcard characters. Wildcard characters are those that can be compared with one or more characters. ‘*’ and ‘?’ are typical wildcard characters where ‘*’ can be compared with zero or more characters (string, str*ng,s*g are same )and ‘?’ can be compared with only one character (string, str?ng are same).

In this program, we will make a function solve() with boolean as a return type, that will return true if the strings match else it will return false. Then we will check whether function returns True or false and prints the respective message to output.

Algorithm:

  • Initialize the variables.
  • Accept the input.
  • Check both the strings character by character.
  • If a character of wild  string contains a ‘*’, take the next character from wild string and check for that character in string which you want to match.
    • If they match, continue checking the next character
    • Else return false.
  • If the character of wild string contains a ‘?’, check if the immediate next character of wild string and the next character of string to be matched.
    • If they match, continue checking  the next characters.
    • Else, return false.
  • Print result.

Python Code:

def solve(a,b):
    n,m=len(a),len(b)
    if n==0 and m==0:
        return True
    if n > 1 and a[0] == ‘*’ and m == 0:
        return False
    if (n > 1 and a[0] == ‘?’or (n != 0 and m !=0 and a[0] == b[0]):
        return solve(a[1:],b[1:]);
    if n !=0 and a[0] == ‘*’:
        return solve(a[1:],bor solve(a,b[1:])
    return False

str1=input(“Enter string containing wild characters:\n)
str2=input(“Enter string to be matched:\n)
print(solve(str1,str2))

Input1:

Enter string containing wild characters:
prep*nsta

Enter string to be matched:
prepinsta

Output1:

True

Input2:

Enter string containing wild characters:
prep*ns*a

Enter string to be matched:
prepster

Output2:

False

C++ program check if two strings match where one string contains wildcard characters