How to print regex match results in python 3?

You need to include .group() after to the match function so that it would print the matched string otherwise it shows only whether a match happened or not. To print the chars which are captured by the capturing groups, you need to pass the corresponding group index to the .group() function.

>>> import re
>>> reg = re.compile("[a-z]+8?")
>>> str = "ccc8"
>>> print(reg.match(str).group())
ccc8

Regex with capturing group.

>>> reg = re.compile("([a-z]+)8?")
>>> print(reg.match(str).group(1))
ccc

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

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.


If you need to get the whole match value, you should use

m = reg.match(r"[a-z]+8?", text)
if m:                          # Always check if a match occurred to avoid NoneType issues
  print(m.group())             # Print the match string

If you need to extract a part of the regex match, you need to use capturing groups in your regular expression. Enclose those patterns with a pair of unescaped parentheses.

To only print captured group results, use Match.groups:

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

So, to get ccc and 8 and display only those, you may use

import re
reg = re.compile("([a-z]+)(8?)")
s = "ccc8"
m = reg.match(s)
if m:
  print(m.groups()) # => ('ccc', '8')

See the Python demo