piton

Regular Expressions in Python

Regular Expressions in Python
In this article, we will take a brief look at regular expressions in python. We will work on built in functions with examples followed by a table which explains what each character means in regular expression for a better understanding.

What is a regular expression?

Before we move towards practical examples, we need to know what a regular expression really is. A regular expression is a sequence of characters which defines the structure of an input or a search pattern. Imagine putting in an email or password on some random website like Facebook, Twitter or Microsoft. Try putting it wrong and by wrong I mean try going against their convention. It will clearly point out those errors for you. You will not be allowed to go to the next step until your input matches the pattern that they have set in the backend. That specific pattern, which restricts you from putting any sort of additional or irrelevant information, is known as regex or regular expression.

Regular Expressions in Python

Regular expressions play no different part in python as in other programming languages. Python contains the module re which provides full support for the usage of regular expressions. Any time an unsuitable or unmatchable information is entered or any sort of error occurs, this re module is going to catch it as an exception which ultimately help solves the required problems.

Regular Expressions patterns

There are a lot of characters available written in a sequence which makes a specific regular expression pattern. Except for control characters, (+ ? . * ^ $ ( ) [ ] | \), all characters match themselves. However, control characters can be escaped by prewriting a backslash.

Following is a table which consists of a pattern and description about their working in python.

Pattern Description
[Pp]ython Match “Python” or “python”
Tub[Ee] Match “TubE” or “Tube”
[aeiou] Match any lower case vowel
[0-9] Match any digit between 0 to 9
[a-z] Match any lowercase ASCII letter
[A-Z] Match any uppercase ASCII letter
[a-zA-Z0-9] Match any lowercase, uppercase ASCII letter
or a digit between 0 to 9
[^aeiou] Match anything but not lowercase vowels
[^0-9] Match anything but not digit
. Match any character except new line
\d Match any digit: [0-9]
\D Match a non-digit: [^0-9]
\s Match white spaces
\S Match non-white spaces
\A Match beginning of string
\Z Match end of string
\w Match word characters
\W Match non-word characters
[… ] Match any single character in brackets
[^… ] Match any single character not in brackets
$ Match the end of line
^ Match the beginning of line

Match and Search Functions in Python

Now, here we are going to see two examples with the two built in functions that exist in python. One is match and the other one is search function. Both of them take the same parameters which are as follows:

Before we jump into example part here is another thing that you need to know. Two methods can be used to get matching groups which are as follows:

What happens is that when match or search functions are used, it makes sub groups of all the related patterns found in strings and structure them at positions starting from 0. See the example below to get a better idea.

Match Function (Example)

In the following example, we have taken a list in which we have used a regular expression which checks the words starting with letter 'a' and will select only if both words start with the same letter i.e.: 'a'.

import re
arraylist = [“affection affect”, “affection act”, “affection Programming”]
for element in arraylist:
k = re.match(“(a\w+)\W(g\w+)”, element)
if k:
print((z.groups()))

Output:

('affection', 'affect')
('affection', 'act')

Third element in the list will not be considered as it doesn't match the regex which says that both words should start with 'a'.

Search Function (Example)

This function is different from match. Search scans through the whole sentence while match does not. In the following example, Search method is successful but match function is not.

import re
Input = “DocumentationNew”
v = re.search(“(ta.*)”, Input)
if v:
print(“result: ” v.group(1))

Output:

result: tationNew

'ta.*' means anything after 'ta' which gives us our result as 'tationNew' from the searched Input “DocumentationNew”.

Conclusion

Regular Expressions are crucial to all software developers and now you can see easily how to use Regular Expressions in the Python programming language.

Open Source Ports of Commercial Game Engines
Free, open source and cross-platform game engine recreations can be used to play old as well as some of the fairly recent game titles. This article wi...
Linux için En İyi Komut Satırı Oyunları
Komut satırı, Linux kullanırken yalnızca en büyük müttefikiniz değil, aynı zamanda eğlence kaynağı da olabilir, çünkü onu özel bir grafik kartı gerekt...
Linux için En İyi Gamepad Eşleme Uygulamaları
Tipik bir klavye ve fare giriş sistemi yerine bir gamepad ile Linux'ta oyun oynamayı seviyorsanız, sizin için bazı faydalı uygulamalar var. Çoğu PC oy...