Regex in Python
Python has a builtin package for regular expressions called re, which is highly useful if you are looking for a pattern in an expression. It comes very handily if you are involved with a lot of scripting and in-text manipulations.
Regular expressions can be tricky and complicated when looked upon, but its quite understandable once you start giving yourself some time, and with some practice. To import a regular expression module in python, we need to use import re, which is also called a regex. while working with regex, I would recommend using a raw string (r) to avoid all the escaping literal meta characters.
Here are the common repetition groups and meta characters with an explanation to be known before jumping to code:
Lets do some examples with regex:
Situation 1:
The O/P for the following will be:
<re.Match object; span=(16, 28), match=’315–751–0000'>
<re.Match object; span=(33, 45), match=’111–222–3333'>
from the output we can observe that it has taken the pattern of all numbers with valid format.
Get Rishi Krishnan Natarajan’s stories in your inbox
Join Medium for free to get updates from this writer.
Situation 2: Now let us say if you want to read the last word in a string
The output for the following will be only successful, similarly if you want to read the first word in a sentence we can use ^ meta character.
Situation 3: Now let us say if you want selected words out of a sentence for example, you are looking for patterns student and professor in this case:
Character set:
A Character set is a group of characters, any one of which can match at that point in the pattern. For example, [ab] would match either a or b. This can also be written as a|b like the bitwise OR operator . So [a-z] means any of the letters in the alphabet will be a match if the input string contains it and [0–3] means the range of numbers (between 0 and three inclusive) will be matched. To get a complement set we use ^, all the characters that are not in the set will be matched. [^b](a|c) implies match either a or c but “not b”
Grouping:
Groupings are marked by the ‘(‘ and ‘)’ meta characters. These are pretty much the same as mathematical expressions; they group together the expressions contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as *,+{3} ; grouping can be nested too
The content of the groupings can be be accessed through group function ->group(N), where N represent the number.
Let’ s see with an example:
The output for the following will be the the numbers 8888 and 9999, as we group(2), for group(1), O/P will be rishi and dhoni
Feel free to comment your thoughts








