-1

Pythex.org is telling me I should be getting 5 matches, but I can't get more than 3 every which way I try. I have searched the internet, the documentation for both re and match objects, used help() I can't figure it out.

>>> z="this is x and this is x and also this is x and x x"
>>> m = re.search('(x+)',z)
>>> m.group(0,1)
('x', 'x')
>>> m.group(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group


>>> m = re.search('(x)',z)
>>> m.group(0,1)
('x', 'x')
>>> m.group(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group

>>> m = re.search(r'(x)',z)
>>> m.group(0,1)
('x', 'x')
>>> m.group(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group

I also tried putting words in between the last x's and that didn't work either.

intwarrior
  • 13
  • 3

1 Answers1

0

In Python, re.search() returns ONLY the first match of the sentence, and nothing after that.

You should try out re.findall(x) in your code.

Always remember, the 0th index of a match (group(0)) returns the complete string which is matched, so it looks like there are two x's matched, but the first one is actually just the string matched by the whole regex.

When you used group(1), only the text within the first parentheses () was returned, which happened to be the same as that of group(0).


TL;DR

Use re.search() for finding out just the first match, and use re.findall() for extracting multiple matches.

Robo Mop
  • 3,485
  • 1
  • 10
  • 23
  • Ah, ya I forgot that group(0) was the complete string. That would also explain my confusion about the m.groups() response. It can get very confusing as a newbie since some functions return back lists and then some return match objects (which are confusing in their own) and the documentation can be very dense and hard to sift through, absorb and retain. Thanks so much, I greatly appreciate the help! – intwarrior Jan 18 '19 at 07:01
  • @intwarrior Don't mention it :) – Robo Mop Jan 18 '19 at 07:03