Python Regular Expression

The regular expression in python used for the search pattern of a string. It used with import "re" module at the beginning of the code.

 

It used some metacharacters which have own separate meaning to search string, her list of metacharacters-

. ^ $ * + ? { } [ ] \ | ( )

Some useful symbol which helps to find string pattern –

\d  -   Matches any decimal digit; this is equivalent to the class [0-9].

 

\D   -  Matches any non-digit character; this is equivalent to the class [^0-9].

 

\s   -   Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].

 

\S  -   Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].

 

\w  -  Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].

 

\W -  Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].

How to use RegEx in Python?

Python uses the in-built "re" module. It can import before starting any regular expression with python:

>>> import re

RegEx Methods  In Python?

RegEx uses different types of functions to search the pattern from the given strings: Here we learn some important python function

  • findall()

  • search

  • split 

  • sub

Use of findall() in RegExp

It returns all matches patterns in the list:

Example:

import re

str = "This is codersarts tutorial"
x = re.findall("is", str)
print(x)

Output:

["is", "is"]

Use of search() in RegExp

It searches the given matches from string and returns it: It returns first matches if more then one matches in the string.

Example:

import re

str = "This is codersarts tutorial"
x = re.
search("\s", str)       #\s for space
print(x)

Output:

3(position of first space in string)

Use of split() in RegExp

By using this string is split at every matching.

Example:

import re

str = "This is codersarts tutorial"
x = re.split("\s", str)       #\s for space search in string
print(x)

Output:

["This", "is", "codersarts", "tutorial"]

Use of sub() in RegExp

It used to replace the matches with the given value in the string.

Example:

import re

str = "This is codersarts tutorial"
x = re.sub("\s", "8",  str)       #\s for space search in string
print(x)

Output:

This8is8codersarts8tutorial

Read complete python regexp, then please visit python official doc -

 

https://docs.python.org/3/howto/regex.html

Contact Us

Tel: (+91) 0120  4118730  

Time :   10 : 00  AM -  08 : 00 PM IST 

Registered address: G-69, Sector 63, 

 Noida - 201301, India

We Provide Services Across The different countries

USA    Australia   Canada   UK    UAE    Singapore   New Zealand    Malasia   India   Ireland   Germany

CodersArts is a Product by Sofstack Technology Solutions Pvt. Ltd.

  • CodersArts | Linkedin
  • Instagram