Python re (regex) search examples

Python regular expression module (re) can be used to find presence of a pattern in a string using re.search. Basic usage of re.search is:

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

Here are some examples.

re.search – ignore case

We can use flag re.I (or re.IGNORECASE) for ignoring case.

import re
m = re.search('world', "Hello WORLD", re.I)
if (m):
  print m.group()
WORLD
Env: Python 2.7.6

re.search – with sub groups

Round brackets in pattern can be used for subgroups matching and can be accessed using m.groups().

import re
m = re.search('(hello)\s+(world)', "a Hello WORLD", re.I)
if (m):
  print m.group()
  print m.groups()
Hello WORLD
('Hello', 'WORLD')
Env: Python 2.7.6

re.search – dot matches all

We can use re.S (or re.DOTALL) to match dot with all characters including newline.

import re
m = re.search('hello.*world', "Hello WORLD\nHello world.", re.I)
print "== when not using re.S =="
if (m):
  print m.group()
m = re.search('hello.*world', "Hello WORLD\nHello world.", re.I|re.S)
print "== when using re.S =="
if (m):
  print m.group()
== when not using re.S ==
Hello WORLD
== when using re.S ==
Hello WORLD
Hello world
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments