Python Program
Write a program to print the following, Given a word W and pattern P, you need to check whether the pattern matches the given word.The word will only contain letters(can be Uppercase and Lowercase). The pattern can contain letters, ? and *.
? : Can be matched with any single letter.
* : Can be matched with any sequence of letters (including an empty sequence).
If the pattern matches with the given word, print True else False.
Sample Input1
3
Hello *l?
Hell He?ll
Hell ?*
Sample Output1
True
False
True
Sample Input1
3
Hello Hell*
Hell He*ll
Hell hell*
Sample Output1
True
True
False
import re
from typing import Pattern
class RegExp:
"""
This class provides matching operations similar to those found in
file system of OS UNIX. But with a restriction syntax, which can
only operate with upper/lower letters and ?, * wildcards.
"""
def __init__(self, word: str, pattern: str):
"""
Constructor
:type word: str
:type pattern: str
"""
assert isinstance(word, str)
assert isinstance(pattern, str)
self.word = word
# convert to a pattern with regular expression wildcards
# i.e. '*' -> '.*' and '?' -> '.'
pattern = pattern.replace('*', '.*')
pattern = pattern.replace('?', '.')
# pattern = re.sub(r'*', '.*', pattern)
# pattern = re.sub(r'?', '.', pattern)
# self.pattern = '^' + pattern + '$'
self.pattern = pattern
def is_match(self):
prog: Pattern[str] = re.compile(self.pattern)
result = prog.fullmatch(self.word)
return bool(result)
def __str__(self):
return str(self.is_match())
r1 = RegExp("Hello", "*l?")
r2 = RegExp("Hell", "He?ll")
r3 = RegExp("Hell", "?*")
r4 = RegExp("Hello", "Hell*")
r5 = RegExp("Hell", "He*ll")
r6 = RegExp("Hell", "hell*")
r7 = RegExp("Stand with Ukraine!", "*wi*?h*!")
# print(r1.pattern)
print(r1)
# print(r2.pattern)
print(r2)
# print(r3.pattern)
print(r3, '\n')
# print(r4.pattern)
print(r4)
# print(r5.pattern)
print(r5)
# print(r6.pattern)
print(r6, '\n')
print(r7, f": \"{r7.word}\" <-- re = r'{r7.pattern}'")
Comments
Leave a comment