How to print regex match results in python 3?

2019-06-26 15:16发布

问题:

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?

回答1:

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.