Flags or modifiers in regular expressions
Syntax | Long Syntax | Description |
---|---|---|
re.I | re.IGNORECASE | It ignores case while matching ie. it will make pattern case insensitive |
re.M | re.MULTILINE | It 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.S | re.DOTALL | It matches all characters including new line character. |
re.U | re.UNICODE | It makes \w, \W, \b, \B to follow Unicode rules. |
re.L | re.LOCALE | It makes \w, \W, \b, \B to follow Locale rules. |
re.X | re.VERBOSE | It 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
- Functions in ‘re’ module(Part II)-findall(), split(), sub()
- Metacharacters or Regular Expression Patterns
- Regular Expression
- Functions in ‘re’ module(Part I)- Match vs Search