Python - re.findall returns unwanted result

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

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

+5
source share
3 answers

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 most pleasant solution:

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

When capture groups findallreturn only captured parts. Use ?:so that the brackets are not a capturing group.

+10
source

, - :

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

All Articles