Pattern Matching With Python

pattern matching with python

Read Time1 Minute, 3 Second

Pattern Matching With Python: If you have to search something from a string, you can write very simple code. Whether its in Python, C++, Java or in anything. Just count the characters, save them in array and compare one by one. Or any other logic.

But if you have to search any particular pattern in a PDF file or some very large document, then it will take very long time to write that code. Well, it will run within a second, but writing it will bore you. 

That is why, regular expressions are used. In python, it is very easy to use. 

Here’s how you can use it for pattern matching.

#Author: Shubham Shrimant
#Code for pattern matching

import re                                       #Importing Regular Expression
pattern=input("pattern")                        #Input function 
string_to_search=input("String")                #Input Function
q=len(re.findall(pattern, string_to_search))    #findall for finding #pattern if matches or not, counting length to return how many times it #is occured
print(q)                                        #printing the count of #pattern in the code

Stringshubham shubham shubham

So, this is a self explanatory code I guess, and I’m sure will help you understand the concept of pattern matching with regular expressions in Python.

Also Read: What is AWS?