WHAT IS PYTHON RegEx AND HOW TO SEARCH USING PYTHON?

RegEx in Python

RegEx stands for Regular Expression. It is a sequence of characters that form a search pattern. RegEx or search pattern can be used to check if a string contains the specified search pattern. Python has a built in package or module called re which can be imported in python code to work with RegEx as shown below.

import re

RegEx Functions

search() – Returns a Match object if there is a match anywhere in the string.

Match Object

It contains the information about search and the result. If there is no match, the value None will be returned, instead of the Match Object. If there is more than one match, only the first occurrence of the match will be returned.

import re
st = "This is a small world"

x = re.search("small", st) 
print(x) #print the Match Object

print("The word small starts from position:",x.start())

Output

<re.Match object; span=(10, 15), match='small'>
The word small starts from position: 10

Match Object Methods- used to retrieve information about the search, and the result:

.span() – Returns a tuple containing the start-, and end positions of the first match occurrence.
.string – Returns the string passed into the function
.group() – Returns the part of the string where there was a match

Example- Below code shows the use of above 3 Match object methods

import re
st = "This is a small world"

x = re.search("small", st) 
print(x) #print the Match Object

print(x.span()) #print the start & end position of first match
print(x.string) #print the string passed in the search func.
print(x.group()) #print the part of the string where is Match

Output

<re.Match object; span=(10, 15), match='small'>
(10, 15)
This is a small world
small

findall() – Returns a list containing all matches

import re

st = "This is a small world"

x = re.findall("small", st)

print(x)

x = re.findall("city", st)
print(x)

Output

['small']
[]

Note- The list contains the matches in the order they are found. If no matches are found, an empty list is returned.

split() – Returns a list where the string has been split at each match

Example- Split at each white space character

import re
st = "This is a small world"

#Split the string at every white-space character:
x = re.split("\s", st)
print(x)

Output

['This', 'is', 'a', 'small', 'world']

We can control the number of occurrences by specifying theย maxsplitย parameter:

Example

Split the string only at the second occurrence:

import re
st = "This is a small world"

#Split the string at second white-space character:
x = re.split("\s", st, 2)
print(x)

Output

['This', 'is', 'a small world']

sub() – Replaces one or many matches with a string

import re
#Replace all white-space characters with the character "-":

st = "This is a small world"
x = re.sub("\s", "-", st)
print(x)

Output

This-is-a-small-world

To control the number of replacements we can use the count parameter as shown below:

Example-

Replace the first 3 occurrences:

import re

#Replace the first 3 occurrences of white-space characters by -
st = "This is a small world"
x = re.sub("\s", "-", st, 3)
print(x)

Output

This-is-a-small world

Metacharacters

Metacharacters are characters with a special meaning:

CharacterDescriptionExample
[]A set of characters“[l-s]”
\Indicates a special sequence (can also be used to escape special characters)“\d”
.Any character (except newline character)“sm..l”
^Starts with“^small”
$Ends with“small$”
*Zero or more occurrences“sm.*l”
+One or more occurrences“sm.+l”
?Zero or one occurrences“sm.?l”
{}Exactly the specified number of occurrences“sm.{2}l”
|Either or“small|is”

Special Sequences

A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:

CharacterDescriptionExample
\AReturns a match if the specified characters are at the beginning of the string“\Asmall”
\bReturns a match where the specified characters are at the beginning or at the end of a word
(the “r” in the beginning is making sure that the string is being treated as a “raw string”)
r”\bld”
r”ld\b”
\BReturns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word
(the “r” in the beginning is making sure that the string is being treated as a “raw string”)
r”\Bld”
r”ald\B”
\dReturns a match where the string contains digits (numbers from 0-9)“\d”
\DReturns a match where the string DOES NOT contain digits“\D”
\sReturns a match where the string contains a white space character“\s”
\SReturns a match where the string DOES NOT contain a white space character“\S”
\wReturns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character)“\w”
\WReturns a match where the string DOES NOT contain any word characters“\W”
\ZReturns a match if the specified characters are at the end of the string“world\Z”

Sets

A set is a set of characters inside a pair of square brackets [] with a special meaning:

SetDescription
[sma]Returns a match where one of the specified characters (s,ย m, or a) is present
[a-l]Returns a match for any lower case character, alphabetically betweenย aย andย l
[^sma]Returns a match for any character EXCEPTย s,ย m, andย a
[012]Returns a match where any of the specified digits (0,ย 1,ย or 2) are present
[0-9]Returns a match for any digit between 0 and 9
[0-5][0-9]Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z]Returns a match for any character alphabetically between a and z, lower case OR upper case
[+]In sets, +*.|()$,{} has no special meaning, so [+] means: return a match for any + character in the string

Search pattern used in the RegEx methods can be a combination of above given Metacharacters, Special Sequences and Sets.

Example- it is using search pattern as “[l-s]” to find the match in string object st.

import re

st = "This is a small world"

x = re.findall("[l-s]", st)

print(x)

Output

['s', 's', 's', 'm', 'l', 'l', 'o', 'r', 'l']

Posted

in

Tags:

Comments

Leave a Reply