AlphaCodingSkills

Python - RegEx


Advertisements

Previous Page Next Page

A RegEx, or Regular Expression is a sequence of characters that defines a search pattern. It is used to check whether a string contains specified search pattern or not. Please see the below mentioned search pattern:

^P....n$

The above search pattern can be used to check whether a string contains six characters which starts with P and ends with n.

Please note that Python has a in-built module re which need to be imported to work with Regular Expression.

Example:

In the below example, ^p....n$ search pattern is checked in string called MyString.

import re

MyString = "Python"
x = re.search("^P....n$", MyString)
if(x):
  print("Pattern found.")
else:
  print("Pattern not found.")


MyString = "Python!."
x = re.search("^P....n$", MyString)
if(x):
  print("Pattern found.")
else:
  print("Pattern not found.")

Output

Pattern found.

Pattern not found.

.


Previous Page Next Page