Python – re.findall returns unwanted result

Question:

re.findall("(100|[0-9][0-9]|[0-9])%", "89%")

This returns only result [89] and I need to return the whole 89%. Any ideas how to do it please?

Asked By: Jakub Turcovsky

||

Answers:

The trivial solution:

>>> re.findall("(100%|[0-9][0-9]%|[0-9]%)","89%")
['89%']

More beautiful solution:

>>> re.findall("(100%|[0-9]{1,2}%)","89%")
['89%']

The prettiest solution:

>>> re.findall("(?:100|[0-9]{1,2})%","89%")
['89%']
Answered By: 0x90
>>> re.findall("(?:100|[0-9][0-9]|[0-9])%", "89%")
['89%']

When there are capture groups findall returns only the captured parts. Use ?: to prevent the parentheses from being a capture group.

Answered By: John Kugelman

Use an outer group, with the inner group a non-capturing group:

>>> re.findall("((?:100|[0-9][0-9]|[0-9])%)","89%")
['89%']
Answered By: user707650
re.findall("/d+/%","89%")

d+ gets a number, regardless of how long.

Answered By: mcklmo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.