-1

when using the pipe character |, how do I get all the results defined in my regex to return?

Or does the .search() method only return the first result found?

Here is my code:

import re

bat.Regex = re.compile(r'Bat(man|mobile|copter|bat)')

matchObject = batRegex.search('Batmobile lost a wheel, Batcopter is not a chopper, his name is Batman, not Batbat')

print(matchObject.group())

Only the first result 'batmobile' is returned, is it possible to return all results?

Thanks!

shaik moeed
  • 5,300
  • 1
  • 18
  • 54

1 Answers1

-1

Please refer to official documentation for "re" module

Excerpts from the docs linked:

  • findall() matches all occurrences of a pattern, not just the first one as search() does.
  • re.search(pattern, string, flags=0) Scan through string looking for the first location where the regular expression and return a corresponding match object.
  • re.findall(pattern, string, flags=0) Return all non-overlapping matches of pattern in string, as a list of strings (Note here: Not a match object which is only one match)
import re
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')

results = batRegex.findall('Batmobile lost a wheel, Batcopter is not a chopper, his name is Batman, not Batbat')
results

output:

['mobile', 'copter', 'man', 'bat']
ELinda
  • 2,658
  • 1
  • 10
  • 9