Regular Expressions

Regular expression is a python built-in module that provides the option to perform regular expressions matching operations.

Match Function

The match function, allows us to check for a match at the beginning of the string. Let’s see an example, to understand how this match function works:

 

import re
string1 = "string is a keyword"
string2 = "We should have a string here"
print(re.match("string",string1, re.IGNORECASE))
print(re.match("string",string2, re.IGNORECASE))

 

Output: None


We can clearly see that the first print only gives us a result while the second print gives a “None” output, this is because the match function will only search at the beginning of the string as mention above.

Search Function

The search function is similar to the match function, but it checks along the entire string. Let’s see the following example:

 

import re
string1 = "This string have the key"
string2 = "This string is empty"
print(re.search("key", string1, re.IGNORECASE))
print(re.search("key", string2, re.IGNORECASE))

 

Output:None


As I said above, this function search for the entire string a given substring. On the first print, it finds the string “key” at the end and on the second print, it doesn’t find the string “key” so it gives a “None” output.
 

Related Tutorials