How to match a pattern and String without using regular expressions in Python
Hello learners, here we are going to learn how to match a pattern and string without regular expressions (regex) in Python. Some may get wrong in understanding the title. Let us see this example to make it simple.
Example-1:
String : BigBunnyBig Pattern: FGF Output: Pattern Found f - BIG G - Bunny
Example-2:
String : BigBunnyBig Pattern: FG Output: Pattern not matched
Now it is clear about pattern matching. Let’s get into the implementation.
The logic is that separate the string into words by the conditions like uppercase or space separated words etc. you may get different ideas to separate. that’s up to your choice.
Implementation
def pattern_matching(str,pattern,str_len,pat_len): #if length of pattern is more than length of string, #then the pattern doesn't matches with string if(str_len<pat_len): return False #if length of string and pattern is 0 then we set it to match if(str_len==0 and pat_len==0): return True #if one is empty and the other is entered then it is mismatched if (str_len == 0 or pat_len == 0): return False #check if string is space separated one or not # if yes then split() function can be used. it just separate the string with the space #if no check the else condition if(str.find(' ')!=-1): str_list=str.split() else: #check for every characters and check for uppercase letters and add it to the list str_list splitted_words = [[str[0]]] for i in str[1:]: if i.isupper() and splitted_words[-1][-1].islower(): splitted_words.append(list(i)) else: splitted_words[-1].append(i) str_list=[''.join(word) for word in splitted_words] #separate the pattern with no repetition for easy logic purpose #those are stored in pat_list pat_list = [] for i in pattern: if(i not in pat_list): pat_list.append(i) #like pattern storing the separated string with no repetition # store that with in the dictionary with pattern characters as corresponding keys j=0 dict = {} for i in pat_list: while(j<str_len): dict[i]=str_list[j] j+=1 break #check for matching conditions #if characters of pattern matches with keys in the dictionary #then store that values in separate list output output=[] for i in pattern: if(i in dict.keys()): output.append(dict[i]) #if output lined with the pattern matches with string #then it matches else not if(output==str_list): print(dict) return True else: return False # Example string and pattern str="CodeSpeedyCode" pattern="MCM" #check for matching conditions string and patterns if(pattern_matching(str,pattern,len(str),len(pattern))): #True conditions print("Pattern Matching") else: #false conditons print("There is no matching found")
Output:
{'M': 'Code', 'C': 'Speedy'} Pattern Matching
Let’s have this
str="CodeSpeedy" pattern="MCM"
Output:
There is no matching found
Testcase3:
str="Code Speedy" pattern="MC"
Output:
{'G': 'Code', 'F': 'Speedy'} Pattern Matching
Also read: re.search vs re.match in Python
Leave a Reply