-1

I am trying to use reluctant quantifier for a group, but it doesn't work as expected. However, the same regex works perfect with online regex tools such as https://regexr.com/.

re.findall(r"(ab)?c", "c")     # this returns [''], when I expect ['c']
re.findall(r"(ab)?c", "abc")   # this returns ['ab'], when I expect ['abc']

I expect the regex r"(ab)?c" to match to 'c' or 'abc'.

What am I missing here?

whitehat
  • 2,381
  • 8
  • 34
  • 47
  • Are you maybe looking at the capture groups instead of the full match? Post your stuff in [regex101](https://regex101.com) and generate code, paste that into your code. It should yield you correct results. – ctwheels Oct 02 '17 at 20:30

1 Answers1

1

From the documentation of re.findall:

If one or more capturing groups are present in the pattern, return a list of groups;

So if your pattern has a group, it will return the group. In your first example it will not return anything because it cannot find the matched group, and the second example will only return the group.

What you seek can be accomplished with re.search https://docs.python.org/3/library/re.html#re.regex.search:

>>> re.search(r"(ab)?c", "c")
<_sre.SRE_Match object; span=(0, 1), match='c'>

>>> re.search(r"(ab)?c", "abc")
<_sre.SRE_Match object; span=(0, 3), match='abc'>

You can retrieve the groups by calling .groups() on the result of the call

If you don't want to search in a string but instead check that the string matches a pattern (and potentially see the groups), use re.match (see search vs match for details on how they differ).

eugecm
  • 1,189
  • 8
  • 14