0

I am learning the findall() method in the regular expression section. I have a problem which I did not find the solution and explanation. The findall() method does not recognize the regular expression pattern correctly or as I expected when I used {} to specify the number of the string for matching.

To be explicity, I take the example from the book. Here is the code:

import re
haRegex = re.compile(r'(Ha){3}')
mo = haRegex.findall('HaHaHaHaHaHa')

when I run the script, I got this:

['Ha', 'Ha']

However, when I replaced (Ha){3} with HaHaHa, I got

['HaHaHa', 'HaHaHa']

which is I expected from the first script.

Besides, the pattern worked perfectly with search() method. I got

'HaHaHa'

with group() method.

Anyone knows what happened?

ᴀʀᴍᴀɴ
  • 3,931
  • 7
  • 32
  • 52
Lin
  • 1
  • 1
  • Use a non-capturing group, `r'(?:Ha){3}'` – Wiktor Stribiżew Jul 25 '18 at 11:52
  • @WiktorStribiżew, it works!!! Thanks a lot. With your solution, I found out that the parenthesizes in the pattern were recognized as grouping. I understand now. Thanks again. – Lin Aug 07 '18 at 01:21

0 Answers0