Match objects

Documentation

  1. class Match in module re
  2. parentheses for grouping
  3. Performing Matches in the Regular Expression HOWTO

Match objects with no grouping

import sys
import re   #regular expressions

filename = "/usr/share/dict/words"

try:
    lines = open(filename)
except FileNotFoundError:
    print(f"Sorry, could not find file \"{filename}\".")
    sys.exit(1)
except PermissionError:
    print(f"Sorry, no permission to open file \"{filename}\".")
    sys.exit(1)

for line in lines:
    line = line.rstrip("\n")   #Remove the trailing newline.
    m = re.search("international", line)   #m is a re.Match
    if m:
        print(line, m.group(), m.start(), m.end())

lines.close()
sys.exit(0)
international international 0 13
internationalism international 0 13
internationalist international 0 13
internationality international 0 13
internationalization international 0 13
internationalize international 0 13
internationally international 0 13
noninternational international 3 16
uninternational international 2 15

Match objects with grouping

    m = re.search(r"^([iu]n)(.+)(ly)$", line)   #m is a re.Match
    if m:
        print(line)
        for i in range(len(m.groups()) + 1):
            print("\t", m.group(i), m.start(i), m.end(i))
inaccessibly
	 inaccessibly 0 12
	 in 0 2
	 accessib 2 10
	 ly 10 12
inaccordantly
	 inaccordantly 0 13
	 in 0 2
	 accordant 2 11
	 ly 11 13

etc.

unyouthfully
	 unyouthfully 0 12
	 un 0 2
	 youthful 2 10
	 ly 10 12
unzealously
	 unzealously 0 11
	 un 0 2
	 zealous 2 9
	 ly 9 11