-1

I'm trying to understand a seemingly easy case while learning regular expressions.

Suppose I have a code like this:

import re

a = "Eventin queue contains 5 elements, first element is 20 minutes old"
b = re.search(r"Eventin queue contains \d+ elements, first element is \d+ minutes old", a)
print(b)

For some reason, bonly returns this result: <_sre.SRE_Match object; span=(0, 66), match='Eventin queue contains 5 elements, first element >

As you can see, it's not a full result that I was expecting. However, if I use re.findall() I get ['Eventin queue contains 5 elements, first element is 20 minutes old']

Am I misunderstanding something here? Shouldn't re.search() return the full match as well?

HeroicOlive
  • 300
  • 2
  • 10
  • Did you take a look at docs? – revo Mar 10 '18 at 23:02
  • 2
    `re.search` returns *a match object* or `None`. This is clearly documented. `re.findall` returns a *list of `str` objets*. Again, this is clearly documented. – juanpa.arrivillaga Mar 10 '18 at 23:02
  • The representation (i.e. printing) of the match object doesn't show you everything that matched, you need to query it. – Peter Wood Mar 10 '18 at 23:03
  • Did you search SO before asking the question? [what-is-the-difference-between-re-search-and-re-match](https://stackoverflow.com/questions/180986/what-is-the-difference-between-re-search-and-re-match/180993) or [python-regex-search-and-findall](https://stackoverflow.com/questions/8110059/python-regex-search-and-findall)? **Research first**, then ask.Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and read it. Both explain various `re`gex methods in detail. – Patrick Artner Mar 10 '18 at 23:04

1 Answers1

4

The method re.findall returns a list of matched substrings, but the method re.search returns a match object, you can recover the full matched substring like this.

b.group() # 'Eventin queue contains 5 elements, first element is 20 minutes old'

What you were seeing, <_sre.SRE_Match object; span=(0, 66), match='Eventin queue contains 5 elements, first element >, is only a representation of the object.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73