Pythonic
Pythonic

Reputation: 173

How to print regex match results in python 3?

I was in IDLE, and decided to use regex to sort out a string. But when I typed in what the online tutorial told me to, all it would do was print:

<_sre.SRE_Match object at 0x00000000031D7E68>

Full program:

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

result:

<_sre.SRE_Match object at 0x00000000031D7ED0>

Could anybody tell me how to actually print the result?

Upvotes: 13

Views: 35085

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

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.

Upvotes: 17

Related Questions