WEB DEVELOPER SITE
PHP7
 

Python - Regular Expressions

A regular expression is a special sequence of characters it find other strings or sets of strings, using a specialized syntax held in a pattern

Regular expressions are widely used in UNIX world.

The module re provides full support for Perl-like regular expressions in Python.

The match Function

This function attempts to match RE pattern to string with optional flags.

Here is the syntax for this function −

re.match(pattern, string, flags=0)

Here is the description of the parameters −

Sr.No. Parameter & Description
1

pattern

This is the regular expression to be matched.

2

string

This is the string, which would be searched to match the pattern at the beginning of string.

3

flags

You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.

re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.

Sr.No. Match Object Method & Description
1

group(num=0)

This method returns entire match (or specific subgroup num)

2

groups()

This method returns all matching subgroups in a tuple (empty if there weren't any)

Example

#!/usr/bin/python
import re

line = "Himalayas (Himadri) are bigger than Himadri"

matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:
   print "matchObj.group() : ", matchObj.group()
   print "matchObj.group(1) : ", matchObj.group(1)
   print "matchObj.group(2) : ", matchObj.group(2)
else:
   print "No match!!"

When the above code is executed, it produces following result
$python main.py
matchObj.group() : Himalayas (Himadri) are bigger than Himadri matchObj.group(1) : Himalayas (Himadri) matchObj.group(2) : bigger
Run Example »

The search Function

This function searches for first occurrence of RE pattern within string with optional flags.

Here is the syntax for this function −

re.search(pattern, string, flags=0)
Sr.No. Parameter & Description
1

pattern

This is the regular expression to be matched.

2

string

This is the string, which would be searched to match the pattern anywhere in the string.

3

flags

You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.

re.search function returns a match object on success, none on failure.
Sr.No. Match Object Methods & Description
1

group(num=0)

This method returns entire match (or specific subgroup num)

2

groups()

This method returns all matching subgroups in a tuple (empty if there weren't any)

#!/usr/bin/python
import re

line = "Human are smarter than elephant";

searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

if searchObj:
   print "searchObj.group() : ", searchObj.group()
   print "searchObj.group(1) : ", searchObj.group(1)
   print "searchObj.group(2) : ", searchObj.group(2)
else:
   print "Nothing found!!"
Run Example »

Matching Versus Searching

When the above code is executed, it produces following result
$python main.py
searchObj.group() : Human are smarter than elephant searchObj.group(1) : Human searchObj.group(2) : smarter
#!/usr/bin/python
import re

line = "Cats are smarter than dogs";

matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
   print "match --> matchObj.group() : ", matchObj.group()
else:
   print "No match!!"

searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
   print "search --> searchObj.group() : ", searchObj.group()
else:
   print "Nothing found!!"

When the above code is executed, it produces the following result −

No match!!
search --> matchObj.group() :  dogs
Run Example »

Search and Replace

One of the most important re methods that use regular expressions is sub.

Syntax

re.sub(pattern, repl, string, max=0)

This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.

#!/usr/bin/python
import re

phone = "2004-959-559 # This is Phone Number"

# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num

# Remove anything other than digits
num = re.sub(r'\D', "", phone)    
print "Phone Num : ", num

When the above code is executed, it produces the following result −

Phone Num :  2004-959-559
Phone Num :  2004959559
Run Example »

Regular Expression Modifiers: Option Flags

Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these

Sr.No. Modifier & Description
1

re.I

Performs case-insensitive matching.

2

re.L

Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior(\b and \B).

3

re.M

Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).

4

re.S

Makes a period (dot) match any character, including a newline.

5

re.U

Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.

6

re.X

Permits "cuter" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker.