Flags for regular expressions(Modifiers)

Flags or modifiers in regular expressions

SyntaxLong SyntaxDescription
re.Ire.IGNORECASEIt ignores case while matching ie. it will make pattern case insensitive
re.Mre.MULTILINEIt makes $ to match the end of a line (not just end of string)
It makes ^ to match the start of a line (not just start of string)
re.Sre.DOTALLIt matches all characters including new line character.
re.Ure.UNICODEIt makes \w, \W, \b, \B to follow Unicode rules.
re.Lre.LOCALEIt makes \w, \W, \b, \B to follow Locale rules.
re.Xre.VERBOSEIt ignores whitespace and allows comments in regex.

To specify more than one of them, use | operator to connect them. For example, re.search(pattern,string,flags=re.IGNORECASE|re.MULTILINE|re.UNICODE).

CODE: Program to show use of MULTILINE flag in regular expression using python.

"""
Author : ITVoyagers (itvoyagers.in)

Date :30th January 2019

Description : Program to show use of MULTILINE flag in regular expression using python.
"""
import re

string = """Site name is Itvoyagers
It is an educational blog for
IT and CS learners."""
regex1 = re.findall(r"^w", string)
#re.M can also b used
regex2 = re.findall(r"^w", string, flags = re.MULTILINE)


print ("without multiline",regex1)    
print ("with multiline",regex2)  

OUTPUT
>>> 
without multiline ['S']
with multiline ['S', 'I', 'I']
>>> 
>>> 

CODE: Program to show use of DOTALL flag in regular expression using python.

"""
Author : ITVoyagers (itvoyagers.in)

Date :30th January 2019

Description : Program to show use of DOTALL flag in regular expression using python.
"""
import re

string = """Site name is Itvoyagers
It is an educational blog for
IT and CS learners."""

regex1 = re.findall(r".+", string)
# we can also use re.S
regex2 = re.findall(r".+", string, re.DOTALL)#includes n

print ("without dotall",regex1)    

print ("with dotall",regex2)    

OUTPUT
>>> 
without dotall ['Site name is Itvoyagers', 'It is an educational blog for', 'IT and CS learners.']
with dotall ['Site name is ItvoyagersnIt is an educational blog fornIT and CS learners.']
>>> 

CODE: Program to show use of IGNORECASE flag in regular expression using python.

"""
Author : ITVoyagers (itvoyagers.in)

Date :30th January 2019

Description : Program to show use of IGNORECASE flag in regular expression using python.
"""
import re

string = """Site name is Itvoyagers
It is an educational blog for
IT and CS learners."""

regex1 = re.findall(r"site", string)
# we can also use re.I
regex2 = re.findall(r"site", string, re.IGNORECASE)#makes string insensitive

print ("without ignorecase",regex1)    

print ("with ignorecase",regex2)    

OUTPUT
>>> 
without ignorecase []
with ignorecase ['Site']
>>> 

You can also check following other posts on regular expression using python here

Leave a Comment